diff --git a/.drone.yml b/.drone.yml index d7bcb8a7d9..947424b302 100644 --- a/.drone.yml +++ b/.drone.yml @@ -18,7 +18,6 @@ steps: - DEBIAN_FRONTEND=noninteractive apt-get -yq install libspandsp3-dev - git clone https://github.com/freeswitch/sofia-sip.git - cd sofia-sip && ./autogen.sh && ./configure.gnu && make -j`nproc` && make install && cd .. - - echo "applications/mod_test" >> modules.conf - echo 'codecs/mod_openh264' >> modules.conf - sed -i '/applications\\/mod_http_cache/s/^#//g' modules.conf - sed -i '/event_handlers\\/mod_rayo/s/^#//g' modules.conf @@ -79,13 +78,13 @@ name: scan-build steps: - name: bootstrap - image: signalwire/freeswitch-public-base:stretch + image: signalwire/freeswitch-public-base pull: always commands: - ./bootstrap.sh -j - name: configure - image: signalwire/freeswitch-public-base:stretch + image: signalwire/freeswitch-public-base pull: always commands: - apt-get update && DEBIAN_FRONTEND=noninteractive apt-get -yq remove libspandsp-dev @@ -116,13 +115,13 @@ steps: - ./configure - name: scan-build - image: signalwire/freeswitch-public-base:stretch + image: signalwire/freeswitch-public-base pull: always commands: - apt-get update && DEBIAN_FRONTEND=noninteractive apt-get -yq remove libspandsp-dev - DEBIAN_FRONTEND=noninteractive apt-get -yq install libsofia-sip-ua-dev libspandsp3-dev - mkdir -p scan-build - - echo '#!/bin/bash\nscan-build-4.0 -o ./scan-build/ make -j`nproc --all` |& tee ./scan-build-result.txt\nexitstatus=$${PIPESTATUS[0]}\necho $$exitstatus > ./scan-build-status.txt\n' > scan.sh + - echo '#!/bin/bash\nscan-build-7 -o ./scan-build/ make -j`nproc --all` |& tee ./scan-build-result.txt\nexitstatus=$${PIPESTATUS[0]}\necho $$exitstatus > ./scan-build-status.txt\n' > scan.sh - chmod +x scan.sh - ./scan.sh - exitstatus=`cat ./scan-build-status.txt` @@ -148,6 +147,6 @@ trigger: --- kind: signature -hmac: 5d5cfb225053294d7cf1a4fed88eaf9a3a53c99a7bad4dc7164eece336c8861a +hmac: a85b0db203d2c9a71c3e4a63a46b5513fbdb3b8f5135e21d0fe0992f33626824 ... diff --git a/.gitignore b/.gitignore index a6cbd8cb92..0461c273de 100644 --- a/.gitignore +++ b/.gitignore @@ -102,6 +102,7 @@ Release/ /build/config/ltmain.sh /build/config/missing /build/freeswitch.pc +/build/standalone_module/freeswitch.pc /build/getlib.sh /build/getg729.sh /build/getsounds.sh @@ -156,6 +157,7 @@ Release/ /src/mod/languages/mod_lua/mod_lua_wrap.cpp.orig /src/mod/languages/mod_perl/mod_perl_wrap.cpp.orig /src/mod/languages/mod_python/mod_python_wrap.cpp.orig +/src/mod/languages/mod_python3/mod_python_wrap.cpp.orig /src/mod/say/mod_say_de/Makefile /src/mod/say/mod_say_es/Makefile /src/mod/say/mod_say_fr/Makefile @@ -264,9 +266,18 @@ src/mod/applications/mod_http_cache/test/test_aws.log src/mod/applications/mod_http_cache/test/test_aws.trs src/mod/formats/mod_sndfile/test/test_sndfile src/mod/formats/mod_sndfile/test/test_sndfile_conf +src/mod/formats/mod_ssml/test/test_tts_format src/mod/*/*/test/*.log src/mod/*/*/test/*.trs src/mod/*/*/test/[0-9]*/* test-suite.log src/mod/applications/mod_av/test/test_BT7.mp4 src/mod/applications/mod_av/test/test_RGB.mp4 +images/test-argb.png +images/test-rgb.png +images/test.png +images/test_patched.png +images/test_text.png + +src/mod/codecs/mod_amrwb/test/test_amrwb +src/mod/endpoints/mod_sofia/test/sipp-based-tests diff --git a/LICENSE b/LICENSE index 6745df1f35..8d2aa962f4 100644 --- a/LICENSE +++ b/LICENSE @@ -3,8 +3,8 @@ Upstream-Name: freeswitch Source: https://freeswitch.org/ Files: * -Copyright: 2005-2014 Anthony Minessale II - 2005-2014 Anthony Minessale II +Copyright: 2005-2022 Anthony Minessale II + 2005-2022 Anthony Minessale II License: MPL-1.1 MOZILLA PUBLIC LICENSE Version 1.1 diff --git a/Makefile.am b/Makefile.am index 8905f06729..739bd29ecb 100644 --- a/Makefile.am +++ b/Makefile.am @@ -248,7 +248,7 @@ endif lib_LTLIBRARIES = libfreeswitch.la libfreeswitch_la_CFLAGS = $(CORE_CFLAGS) $(SQLITE_CFLAGS) $(GUMBO_CFLAGS) $(FVAD_CFLAGS) $(FREETYPE_CFLAGS) $(CURL_CFLAGS) $(PCRE_CFLAGS) $(SPEEX_CFLAGS) $(LIBEDIT_CFLAGS) $(openssl_CFLAGS) $(SOFIA_SIP_CFLAGS) $(AM_CFLAGS) $(TPL_CFLAGS) libfreeswitch_la_LDFLAGS = -version-info 1:0:0 $(AM_LDFLAGS) $(PLATFORM_CORE_LDFLAGS) -no-undefined -libfreeswitch_la_LIBADD = $(CORE_LIBS) $(APR_LIBS) $(SQLITE_LIBS) $(GUMBO_LIBS) $(FVAD_LIBS) $(FREETYPE_LIBS) $(CURL_LIBS) $(PCRE_LIBS) $(SPEEX_LIBS) $(LIBEDIT_LIBS) $(openssl_LIBS) $(PLATFORM_CORE_LIBS) $(TPL_LIBS) $(SPANDSP_LIBS) $(SOFIA_SIP_LIBS) +libfreeswitch_la_LIBADD = $(CORE_LIBS) $(APR_LIBS) $(SQLITE_LIBS) $(GUMBO_LIBS) $(FVAD_LIBS) $(FREETYPE_LIBS) $(CURL_LIBS) $(PCRE_LIBS) $(SPEEX_LIBS) $(LIBEDIT_LIBS) $(SYSTEMD_LIBS) $(openssl_LIBS) $(PLATFORM_CORE_LIBS) $(TPL_LIBS) $(SPANDSP_LIBS) $(SOFIA_SIP_LIBS) libfreeswitch_la_DEPENDENCIES = $(BUILT_SOURCES) if HAVE_PNG @@ -300,6 +300,7 @@ library_include_HEADERS = \ src/include/switch_dso.h \ src/include/switch_loadable_module.h \ src/include/switch_module_interfaces.h \ + src/include/switch_packetizer.h \ src/include/switch_platform.h \ src/include/switch_resample.h \ src/include/switch_regex.h \ @@ -309,6 +310,7 @@ library_include_HEADERS = \ src/include/switch_jitterbuffer.h \ src/include/switch_estimators.h \ src/include/switch_rtcp_frame.h \ + src/include/switch_spandsp.h \ src/include/switch_stun.h \ src/include/switch_nat.h \ src/include/switch_log.h \ @@ -364,6 +366,7 @@ libfreeswitch_la_SOURCES = \ src/switch_version.c \ src/switch_core_media.c \ src/switch_core_video.c \ + src/switch_packetizer.c \ src/switch_sdp.c \ src/switch_scheduler.c \ src/switch_core_db.c \ @@ -383,6 +386,7 @@ libfreeswitch_la_SOURCES = \ src/switch_ivr_say.c \ src/switch_ivr_menu.c \ src/switch_ivr.c \ + src/switch_spandsp.c \ src/switch_stun.c \ src/switch_nat.c \ src/switch_log.c \ @@ -742,7 +746,7 @@ pristine: git clean -fdx git reset --hard -update-clean: clean python-reconf +update-clean: clean python-reconf python3-reconf cd libs/esl && $(MAKE) clean cd libs/srtp && $(MAKE) clean @@ -759,6 +763,10 @@ python-reconf: rm -f src/mod/languages/mod_python/Makefile ./config.status +python3-reconf: + rm -f src/mod/languages/mod_python3/Makefile + ./config.status + reconf: rm config.cache sh ./config.status --recheck diff --git a/build/freeswitch.service b/build/freeswitch.service index ae6921b4df..2b0a035723 100644 --- a/build/freeswitch.service +++ b/build/freeswitch.service @@ -4,6 +4,10 @@ After=syslog.target network.target After=postgresql.service postgresql-9.3.service postgresql-9.4.service mysqld.service httpd.service [Service] +# You can use Type=notify only if you compile FreeSWITCH with --enable-systemd configure option +# In this case you have to run FreeSWITCH in foreground mode (-nf option)! +#Type=notify +#NotifyAccess=main User=freeswitch EnvironmentFile=-/etc/sysconfig/freeswitch # RuntimeDirectory is not yet supported in CentOS 7. A workaround is to use /etc/tmpfiles.d/freeswitch.conf diff --git a/build/modmake.rules.in b/build/modmake.rules.in index dbce9bd48e..7f880b86f9 100644 --- a/build/modmake.rules.in +++ b/build/modmake.rules.in @@ -188,7 +188,7 @@ $(MODNAME).o: $(MODDIR)/$(SOURCEFILE) \ $(switch_srcdir)/src/include/switch_event.h $(switch_srcdir)/src/include/switch_resample.h \ $(switch_srcdir)/src/include/switch_ivr.h $(switch_srcdir)/src/include/switch_rtp.h \ $(switch_srcdir)/src/include/switch_stun.h $(switch_srcdir)/src/include/switch_log.h \ - $(switch_srcdir)/src/include/switch_xml.h + $(switch_srcdir)/src/include/switch_xml.h $(switch_srcdir)/src/include/switch_spandsp.h @echo Compiling $<... if test -f "$(CSOURCEFILE)" -o -f "$(MODDIR)/$(CSOURCEFILE)"; then \ if test ! -z $(VERBOSE) ; then echo $(COMPILE) -c -o $@ `test -f '$<' || echo '$(MODDIR)/'`$< ; fi ;\ @@ -211,7 +211,7 @@ $(MODNAME).lo: $(MODDIR)/$(SOURCEFILE) \ $(switch_srcdir)/src/include/switch_event.h $(switch_srcdir)/src/include/switch_resample.h \ $(switch_srcdir)/src/include/switch_ivr.h $(switch_srcdir)/src/include/switch_rtp.h \ $(switch_srcdir)/src/include/switch_stun.h $(switch_srcdir)/src/include/switch_log.h \ - $(switch_srcdir)/src/include/switch_xml.h + $(switch_srcdir)/src/include/switch_xml.h $(switch_srcdir)/src/include/switch_spandsp.h @echo Compiling $<... if test -f "$(CSOURCEFILE)" -o -f "$(MODDIR)/$(CSOURCEFILE)"; then \ if test ! -z $(VERBOSE) ; then echo $(LTCOMPILE) -c -o $@ `test -f '$<' || echo '$(MODDIR)/'`$< ; fi ;\ @@ -261,6 +261,8 @@ $(switch_srcdir)/src/include/switch_ivr.h: $(switch_srcdir)/src/include/switch_rtp.h: +$(switch_srcdir)/src/include/switch_spandsp.h: + $(switch_srcdir)/src/include/switch_stun.h: $(switch_srcdir)/src/include/switch_log.h: diff --git a/build/modules.conf.in b/build/modules.conf.in index b38900047b..feb902994b 100644 --- a/build/modules.conf.in +++ b/build/modules.conf.in @@ -49,6 +49,7 @@ applications/mod_sms applications/mod_spandsp #applications/mod_spy #applications/mod_stress +applications/mod_test #applications/mod_translate applications/mod_valet_parking #applications/mod_video_filter @@ -134,6 +135,7 @@ languages/mod_lua #languages/mod_managed #languages/mod_perl #languages/mod_python +#languages/mod_python3 #languages/mod_v8 #languages/mod_yaml loggers/mod_console diff --git a/build/modules.conf.most b/build/modules.conf.most index 6f976dca38..a981c273db 100644 --- a/build/modules.conf.most +++ b/build/modules.conf.most @@ -47,6 +47,7 @@ applications/mod_soundtouch applications/mod_spandsp applications/mod_spy applications/mod_stress +applications/mod_test applications/mod_translate applications/mod_valet_parking applications/mod_video_filter @@ -127,7 +128,7 @@ languages/mod_java languages/mod_lua languages/mod_managed languages/mod_perl -languages/mod_python +languages/mod_python3 #languages/mod_v8 languages/mod_yaml loggers/mod_console diff --git a/build/next-release.txt b/build/next-release.txt index ef3ef34409..924b6af807 100644 --- a/build/next-release.txt +++ b/build/next-release.txt @@ -1 +1 @@ -1.10.7-dev +1.10.8-dev diff --git a/build/swigall.sh b/build/swigall.sh index ee7abf19cd..44b05b633b 100755 --- a/build/swigall.sh +++ b/build/swigall.sh @@ -13,6 +13,11 @@ make swigclean make mod_python_wrap.cpp cd ../../../.. +cd src/mod/languages/mod_python3 +make swigclean +make mod_python_wrap.cpp +cd ../../../.. + cd src/mod/languages/mod_java make reswig cd ../../../.. diff --git a/conf/FreeMono.ttf b/conf/FreeMono.ttf new file mode 100644 index 0000000000..c4200565a7 Binary files /dev/null and b/conf/FreeMono.ttf differ diff --git a/conf/curl/autoload_configs/timezones.conf.xml b/conf/curl/autoload_configs/timezones.conf.xml index 397e9a979f..14f87f8c67 100644 --- a/conf/curl/autoload_configs/timezones.conf.xml +++ b/conf/curl/autoload_configs/timezones.conf.xml @@ -184,7 +184,7 @@ - + diff --git a/conf/insideout/autoload_configs/modules.conf.xml b/conf/insideout/autoload_configs/modules.conf.xml index 5078503489..9408bcd29f 100644 --- a/conf/insideout/autoload_configs/modules.conf.xml +++ b/conf/insideout/autoload_configs/modules.conf.xml @@ -81,6 +81,7 @@ + diff --git a/conf/insideout/autoload_configs/timezones.conf.xml b/conf/insideout/autoload_configs/timezones.conf.xml index 397e9a979f..14f87f8c67 100644 --- a/conf/insideout/autoload_configs/timezones.conf.xml +++ b/conf/insideout/autoload_configs/timezones.conf.xml @@ -184,7 +184,7 @@ - + diff --git a/conf/minimal/autoload_configs/timezones.conf.xml b/conf/minimal/autoload_configs/timezones.conf.xml index 757d16c19d..0af4c77d7f 100644 --- a/conf/minimal/autoload_configs/timezones.conf.xml +++ b/conf/minimal/autoload_configs/timezones.conf.xml @@ -196,7 +196,7 @@ - + diff --git a/conf/rayo/autoload_configs/timezones.conf.xml b/conf/rayo/autoload_configs/timezones.conf.xml index 397e9a979f..14f87f8c67 100644 --- a/conf/rayo/autoload_configs/timezones.conf.xml +++ b/conf/rayo/autoload_configs/timezones.conf.xml @@ -184,7 +184,7 @@ - + diff --git a/conf/sbc/autoload_configs/timezones.conf.xml b/conf/sbc/autoload_configs/timezones.conf.xml index 397e9a979f..14f87f8c67 100644 --- a/conf/sbc/autoload_configs/timezones.conf.xml +++ b/conf/sbc/autoload_configs/timezones.conf.xml @@ -184,7 +184,7 @@ - + diff --git a/conf/testing/autoload_configs/timezones.conf.xml b/conf/testing/autoload_configs/timezones.conf.xml index 757d16c19d..0af4c77d7f 100644 --- a/conf/testing/autoload_configs/timezones.conf.xml +++ b/conf/testing/autoload_configs/timezones.conf.xml @@ -196,7 +196,7 @@ - + diff --git a/conf/testing/sip_profiles/internal.xml b/conf/testing/sip_profiles/internal.xml index 2a3564ebb4..d7b2ef893d 100644 --- a/conf/testing/sip_profiles/internal.xml +++ b/conf/testing/sip_profiles/internal.xml @@ -216,6 +216,14 @@ + + + diff --git a/conf/vanilla/autoload_configs/modules.conf.xml b/conf/vanilla/autoload_configs/modules.conf.xml index 8eff5fe263..b5a58d1580 100644 --- a/conf/vanilla/autoload_configs/modules.conf.xml +++ b/conf/vanilla/autoload_configs/modules.conf.xml @@ -122,6 +122,7 @@ + diff --git a/conf/vanilla/autoload_configs/spandsp.conf.xml b/conf/vanilla/autoload_configs/spandsp.conf.xml index 2471ca52ce..6345512908 100644 --- a/conf/vanilla/autoload_configs/spandsp.conf.xml +++ b/conf/vanilla/autoload_configs/spandsp.conf.xml @@ -28,6 +28,7 @@ + diff --git a/conf/vanilla/autoload_configs/timezones.conf.xml b/conf/vanilla/autoload_configs/timezones.conf.xml index 50bd7f3760..48206d1ce4 100644 --- a/conf/vanilla/autoload_configs/timezones.conf.xml +++ b/conf/vanilla/autoload_configs/timezones.conf.xml @@ -197,7 +197,7 @@ - + diff --git a/conf/vanilla/autoload_configs/verto.conf.xml b/conf/vanilla/autoload_configs/verto.conf.xml index 899aaeb6c2..91f75f11e9 100644 --- a/conf/vanilla/autoload_configs/verto.conf.xml +++ b/conf/vanilla/autoload_configs/verto.conf.xml @@ -2,6 +2,7 @@ + diff --git a/conf/vanilla/sip_profiles/internal-ipv6.xml b/conf/vanilla/sip_profiles/internal-ipv6.xml index 21bb1f1e77..f067ae7482 100644 --- a/conf/vanilla/sip_profiles/internal-ipv6.xml +++ b/conf/vanilla/sip_profiles/internal-ipv6.xml @@ -36,6 +36,8 @@ + + diff --git a/conf/vanilla/sip_profiles/internal.xml b/conf/vanilla/sip_profiles/internal.xml index 58350e827b..749e4b0687 100644 --- a/conf/vanilla/sip_profiles/internal.xml +++ b/conf/vanilla/sip_profiles/internal.xml @@ -172,6 +172,8 @@ + + @@ -216,6 +218,14 @@ + + + diff --git a/configure.ac b/configure.ac index 25f01e8f0b..baec8b2b83 100644 --- a/configure.ac +++ b/configure.ac @@ -3,10 +3,10 @@ # Must change all of the below together # For a release, set revision for that tagged release as well and uncomment -AC_INIT([freeswitch], [1.10.7-dev], bugs@freeswitch.org) +AC_INIT([freeswitch], [1.10.8-dev], bugs@freeswitch.org) AC_SUBST(SWITCH_VERSION_MAJOR, [1]) AC_SUBST(SWITCH_VERSION_MINOR, [10]) -AC_SUBST(SWITCH_VERSION_MICRO, [7-dev]) +AC_SUBST(SWITCH_VERSION_MICRO, [8-dev]) AC_SUBST(SWITCH_VERSION_REVISION, []) AC_SUBST(SWITCH_VERSION_REVISION_HUMAN, []) @@ -598,7 +598,7 @@ AC_ARG_ENABLE(srtp, AM_CONDITIONAL([ENABLE_SRTP],[test "${enable_srtp}" = "yes"]) have_openal=no -AC_CHECK_LIB(openal, alMidiGainSOFT, [have_openal="yes"]) +AC_CHECK_LIB(openal, alcLoopbackOpenDeviceSOFT, [have_openal="yes"]) AM_CONDITIONAL([HAVE_OPENAL],[test "${have_openal}" = "yes"]) AC_ARG_ENABLE(zrtp, @@ -725,7 +725,7 @@ PKG_CHECK_MODULES([SPANDSP], [spandsp >= 3.0],[ AC_MSG_ERROR([no usable spandsp; please install spandsp3 devel package or equivalent]) ]) -PKG_CHECK_MODULES([SOFIA_SIP], [sofia-sip-ua >= 1.13.5],[ +PKG_CHECK_MODULES([SOFIA_SIP], [sofia-sip-ua >= 1.13.6],[ AM_CONDITIONAL([HAVE_SOFIA_SIP],[true])],[ AC_MSG_ERROR([no usable sofia-sip; please install sofia-sip-ua devel package or equivalent]) ]) @@ -883,7 +883,7 @@ AC_SUBST(LIBTOOL_LIB_EXTEN) # Checks for header files. AC_HEADER_DIRENT AC_HEADER_STDC -AC_CHECK_HEADERS([sys/types.h sys/resource.h sched.h wchar.h sys/filio.h sys/ioctl.h sys/prctl.h sys/select.h netdb.h execinfo.h sys/time.h]) +AC_CHECK_HEADERS([sys/types.h sys/resource.h sched.h wchar.h sys/filio.h sys/ioctl.h sys/prctl.h sys/select.h netdb.h sys/time.h]) # Solaris 11 privilege management AS_CASE([$host], @@ -1408,7 +1408,9 @@ PKG_CHECK_MODULES([VLC], [libvlc >= 2.1.0],[ PKG_CHECK_MODULES([OPENCV], [opencv >= 2.4.5],[ AM_CONDITIONAL([HAVE_OPENCV],[true])],[ - AC_MSG_RESULT([no]); AM_CONDITIONAL([HAVE_OPENCV],[false])]) + PKG_CHECK_MODULES([OPENCV], [opencv4 >= 2.4.5],[ + AM_CONDITIONAL([HAVE_OPENCV],[true])],[ + AC_MSG_RESULT([no]); AM_CONDITIONAL([HAVE_OPENCV],[false])])]) PKG_CHECK_MODULES([OPUSFILE_DECODE], [opusfile >= 0.5],[ AM_CONDITIONAL([HAVE_OPUSFILE_DECODE],[true])],[ @@ -1529,11 +1531,25 @@ PKG_CHECK_MODULES([V8FS_STATIC], [v8-6.1_static >= 6.1.298],[ PKG_CHECK_MODULES([KS], [libks >= 1.1.0],[ AM_CONDITIONAL([HAVE_KS],[true])],[ - AC_MSG_RESULT([no]); AM_CONDITIONAL([HAVE_KS],[false])]) + if module_enabled mod_verto; then + AC_MSG_ERROR([You need to either install libks or disable mod_verto in modules.conf]) + else + if module_enabled mod_signalwire; then + AC_MSG_ERROR([You need to either install libks or disable mod_signalwire in modules.conf]) + else + AC_MSG_RESULT([no]); AM_CONDITIONAL([HAVE_KS],[false]) + fi + fi +]) PKG_CHECK_MODULES([SIGNALWIRE_CLIENT], [signalwire_client >= 1.0.0],[ AM_CONDITIONAL([HAVE_SIGNALWIRE_CLIENT],[true])],[ - AC_MSG_RESULT([no]); AM_CONDITIONAL([HAVE_SIGNALWIRE_CLIENT],[false])]) + if module_enabled mod_signalwire; then + AC_MSG_ERROR([You need to either install signalwire-client-c or disable mod_signalwire in modules.conf]) + else + AC_MSG_RESULT([no]); AM_CONDITIONAL([HAVE_SIGNALWIRE_CLIENT],[false]) + fi +]) PKG_CHECK_MODULES([AMQP], [librabbitmq >= 0.5.2],[ AM_CONDITIONAL([HAVE_AMQP],[true])],[ @@ -1576,6 +1592,17 @@ AS_IF([test "x$enable_core_libedit_support" != "xno"],[ AC_MSG_ERROR([You need to either install libedit-dev (>= 2.11) or configure with --disable-core-libedit-support]) ])])]) +AC_ARG_ENABLE(systemd, + [AS_HELP_STRING([--enable-systemd], [Compile with systemd notify support])]) + +AS_IF([test "x$enable_systemd" = "xyes"],[ + PKG_CHECK_MODULES([SYSTEMD], [libsystemd >= 219], [ + AC_DEFINE([HAVE_SYSTEMD], [1], [Define to 1 if systemd is available])]) +]) + +AC_SUBST(SYSTEMD_LIBS) + + dnl --------------------------------------------------------------------------- dnl - OpenLDAP SDK dnl --------------------------------------------------------------------------- @@ -1702,7 +1729,7 @@ if test "x$ac_cv_have_php" != "xno" -a "x$ac_cv_have_php_config" != "xno"; then fi # -# Python checks for mod_python +# Python checks for mod_python (scroll down to see python3 checks for mod_python3) # AC_ARG_WITH( [python], @@ -1822,6 +1849,127 @@ else AC_MSG_WARN([python support disabled, building mod_python will fail!]) fi +# +# Python3 checks for mod_python3 +# +AC_ARG_WITH( + [python3], + [AS_HELP_STRING([--with-python3], [Use system provided version of python3 (default: try)])], + [with_python3="$withval"], + [with_python3="try"] +) + +if test "$with_python3" != "no" +then + save_CFLAGS="$CFLAGS" + save_LIBS="$LIBS" + + if test "$with_python3" != "yes" -a "$with_python3" != "try" ; then + AC_MSG_CHECKING([for python3]) + if test ! -x "$with_python3" ; then + AC_MSG_ERROR([Specified python3 does not exist or is not executable: $with_python3]) + fi + AC_MSG_RESULT([$with_python3]) + AC_SUBST([PYTHON3], ["$with_python3"]) + else + AC_PATH_PROG([PYTHON3], ["python3"], ["no"], ["$PATH:/usr/bin:/usr/local/bin"]) + fi + + if test "$PYTHON3" != "no" ; then + AC_MSG_CHECKING([python3 version]) + PYTHON3_VER="`$PYTHON3 -V 2>&1 | cut -d' ' -f2`" + + if test -z "$PYTHON3_VER" ; then + AC_MSG_ERROR([Unable to detect python3 version]) + fi + AC_MSG_RESULT([$PYTHON3_VER]) + + AC_MSG_CHECKING([for python3 distutils]) + python3_result="`$PYTHON3 -c 'import distutils;' 2>&1`" + if test -z "$python3_result" ; then + python3_has_distutils="yes" + else + python3_has_distutils="no" + fi + AC_MSG_RESULT([$python3_has_distutils]) + + if test "$python3_has_distutils" != "no" ; then + AC_MSG_CHECKING([location of python3 site-packages]) + + PYTHON3_SITE_DIR="`$PYTHON3 -c 'from distutils import sysconfig; print(sysconfig.get_python_lib(0));'`" + + if test -z "$PYTHON3_SITE_DIR" ; then + AC_MSG_ERROR([Unable to detect python3 site-packages path]) + elif test ! -d "$PYTHON3_SITE_DIR" ; then + AC_MSG_ERROR([Path $PYTHON3_SITE_DIR returned by python3 does not exist!]) + fi + AC_MSG_RESULT([$PYTHON3_SITE_DIR]) + AC_SUBST([PYTHON3_SITE_DIR], [$PYTHON3_SITE_DIR]) + + # + # python3 distutils found, get settings from python3 directly + # + PYTHON3_CFLAGS="`$PYTHON3 -c 'from distutils import sysconfig; flags = [[\"-I\" + sysconfig.get_python_inc(0), \"-I\" + sysconfig.get_python_inc(1), \" \".join(sysconfig.get_config_var(\"CFLAGS\").split())]]; print(\" \".join(flags));' | sed -e 's/-arch i386//g;s/-arch x86_64//g'`" + PYTHON3_LDFLAGS="`$PYTHON3 -c 'from distutils import sysconfig; ldver = sysconfig.get_config_var(\"LDVERSION\"); libs = sysconfig.get_config_var(\"LIBS\").split() + sysconfig.get_config_var(\"SYSLIBS\").split(); libs.append(\"-lpython\" + [[ldver,sysconfig.get_config_var(\"VERSION\")]][[ldver==None]]); print(\" \".join(libs));'`" + PYTHON3_LIB="`$PYTHON3 -c 'from distutils import sysconfig; ldver = sysconfig.get_config_var(\"LDVERSION\"); print(\"python\" + [[ldver,sysconfig.get_config_var(\"VERSION\")]][[ldver==None]]);'`" + PYTHON3_LIBDIR="`$PYTHON3 -c 'from distutils import sysconfig; print(sysconfig.get_config_var(\"LIBDIR\"));'`" + + # handle python3 being installed into /usr/local + AC_MSG_CHECKING([python3 libdir]) + if test -z "`echo $PYTHON3_LIBDIR | grep "/usr/lib"`" ; then + PYTHON3_LDFLAGS="-L$PYTHON3_LIBDIR $PYTHON3_LDFLAGS" + LIBS="-L$PYTHON3_LIBDIR $LIBS" + fi + AC_MSG_RESULT([$PYTHON3_LIBDIR]) + + # check libpython3 + AC_CHECK_LIB([$PYTHON3_LIB], [main], [has_libpython3="yes"], [has_libpython3="no"]) + + if test "$has_libpython3" = "no" ; then + AS_IF([test "$with_python3" = "try"], + [AC_MSG_WARN([$PYTHON3_LIB is unusable])], + [AC_MSG_ERROR([$PYTHON3_LIB is unusable])] + ) + fi + + # check whether system libpython3 is usable and has threads support + CFLAGS="$PYTHON3_CFLAGS" + LIBS="$PYTHON3_LDFLAGS" + AC_CHECK_FUNC([PyThread_init_thread], [python3_has_threads="yes"], [python3_has_threads="no"]) + + if test "$python3_has_threads" = "no"; then + AS_IF([test "$with_python3" = "try"], + [AC_MSG_WARN([Your python3 lacks threads support, can not build mod_python3])], + [AC_MSG_ERROR([Your python3 lacks threads support, can not build mod_python3])] + ) + else + AC_MSG_NOTICE([Your python3 seems OK, do not forget to enable mod_python3 in modules.conf]) + AC_SUBST([PYTHON3_CFLAGS], [$PYTHON3_CFLAGS]) + AC_SUBST([PYTHON3_LDFLAGS], [$PYTHON3_LDFLAGS]) + fi + else + AS_IF([test "$with_python3" = "try"], + [AC_MSG_WARN([Could not find or use python3 distutils module: $python3_result])], + [AC_MSG_ERROR([Could not find or use python3 distutils module: $python3_result])] + ) + fi + + LIBS="$save_LIBS" + CFLAGS="$save_CFLAGS" + + unset python3_has_threads + unset python3_has_distutils + unset python3_result + else + AS_IF([test "$with_python3" = "try"], + [AC_MSG_WARN([Could not find python3, mod_python3 will not build, use --with-python3 to specify the location])], + [AC_MSG_ERROR([Could not find python3, use --with-python3 to specify the location])] + ) + fi +else + AC_MSG_WARN([python3 support disabled, building mod_python3 will fail!]) +fi + # # SNMP checks for mod_snmp # @@ -1852,6 +2000,55 @@ if test "${enable_address_sanitizer}" = "yes"; then APR_ADDTO(LDFLAGS, -fsanitize=address) fi +# Enable HEAP profiler (requires libgoogle-perftools-dev package) +AC_ARG_ENABLE(heap_profiler, + [AC_HELP_STRING([--enable-heap-profiler],[build with google heap profiler])], + [enable_heap_profiler="$enable_heap_profiler"], + [enable_heap_profiler="no"]) + +# Enable CPU profiler (requires libgoogle-perftools-dev package) +AC_ARG_ENABLE(cpu_profiler, + [AC_HELP_STRING([--enable-cpu-profiler],[build with google cpu profiler])], + [enable_cpu_profiler="$enable_cpu_profiler"], + [enable_cpu_profiler="no"]) + +PKG_CHECK_MODULES([TCMALLOC], [libtcmalloc], [have_tcmalloc=yes], [have_tcmalloc=no]) + +if test "${enable_heap_profiler}" = "yes" || test "${enable_cpu_profiler}" = "yes"; then + if test "x$have_tcmalloc" != "xyes" ; then + AC_MSG_ERROR([You must install libgoogle-perftools-dev in order to use heap or cpu profiler]) + fi +fi + +# WARNING: When both enabled you can NOT link them statically and MUST use the special library +if test "${enable_heap_profiler}" = "yes" && test "${enable_cpu_profiler}" = "yes"; then + APR_ADDTO(CFLAGS, -ltcmalloc_and_profiler) + APR_ADDTO(CXXFLAGS, -ltcmalloc_and_profiler) + APR_ADDTO(LDFLAGS, -ltcmalloc_and_profiler) +else + if test "${enable_heap_profiler}" = "yes"; then + APR_ADDTO(CFLAGS, -ltcmalloc) + APR_ADDTO(CXXFLAGS, -ltcmalloc) + APR_ADDTO(LDFLAGS, -ltcmalloc) + fi + + if test "${enable_cpu_profiler}" = "yes"; then + APR_ADDTO(CFLAGS, -lprofiler) + APR_ADDTO(CXXFLAGS, -lprofiler) + APR_ADDTO(LDFLAGS, -lprofiler) + fi +fi + +# Enable fake dlclose +AC_ARG_ENABLE(fake_dlclose, + [AC_HELP_STRING([--enable-fake-dlclose],[Do not unload dynamic libraries])], + [enable_fake_dlclose="$enable_fake_dlclose"], + [enable_fake_dlclose="no"]) + +if test "${enable_fake_dlclose}" = "yes"; then + APR_ADDTO(SWITCH_AM_CFLAGS, -DHAVE_FAKE_DLCLOSE) +fi + AC_ARG_ENABLE(, [AC_HELP_STRING([--enable-pool-sanitizer],[build with sanitizer friendly pool behavior])], [enable_pool_sanitizer="$enable_pool_sanitizer"], @@ -2012,6 +2209,7 @@ AC_CONFIG_FILES([Makefile src/mod/languages/mod_managed/Makefile src/mod/languages/mod_perl/Makefile src/mod/languages/mod_python/Makefile + src/mod/languages/mod_python3/Makefile src/mod/languages/mod_v8/Makefile src/mod/languages/mod_yaml/Makefile src/mod/languages/mod_basic/Makefile diff --git a/debian/bootstrap.sh b/debian/bootstrap.sh index 981e2c42eb..fd5ff75cf0 100755 --- a/debian/bootstrap.sh +++ b/debian/bootstrap.sh @@ -29,7 +29,7 @@ conf_dir="../conf" lang_dir="../conf/vanilla/lang" fs_description="FreeSWITCH is a scalable open source cross-platform telephony platform designed to route and interconnect popular communication protocols using audio, video, text or any other form of media." mod_build_depends="." mod_depends="." mod_recommends="." mod_suggests="." -supported_debian_distros="wheezy jessie stretch buster sid" +supported_debian_distros="wheezy jessie stretch buster bullseye sid" supported_ubuntu_distros="trusty utopic xenial" supported_distros="$supported_debian_distros $supported_ubuntu_distros" avoid_mods=( @@ -299,7 +299,7 @@ print_source_control () { esac local debhelper_dep="debhelper (>= 8.0.0)" if [ ${use_sysvinit} = "false" ]; then - debhelper_dep=${debhelper_dep}", dh-systemd" + debhelper_dep=${debhelper_dep}", dh-systemd | debhelper (>= 8.0.0)" fi cat <= 0.90) | dh-python, erlang-dev, libtpl-dev (>= 1.5), + python-dev | python-dev-is-python2, python3-dev, python-all-dev, python-support (>= 0.90) | dh-python, erlang-dev, libtpl-dev (>= 1.5), # documentation doxygen, # for APR (not essential for build) uuid-dev, libexpat1-dev, libgdbm-dev, libdb-dev, # used by many modules libcurl4-openssl-dev | libcurl4-gnutls-dev | libcurl-dev, - bison, zlib1g-dev, libsofia-sip-ua-dev (>= 1.13.5), + bison, zlib1g-dev, libsofia-sip-ua-dev (>= 1.13.6), libspandsp3-dev, # used to format the private freeswitch apt-repo key properly gnupg, @@ -371,7 +371,7 @@ Description: Cross-Platform Scalable Multi-Protocol Soft Switch Package: libfreeswitch1 Architecture: amd64 armhf -Depends: \${shlibs:Depends}, \${misc:Depends} +Depends: \${shlibs:Depends}, \${misc:Depends}, libsofia-sip-ua0 (>= 1.13.6) Recommends: Suggests: libfreeswitch1-dbg Conflicts: freeswitch-all (<= 1.6.7) @@ -683,7 +683,7 @@ Depends: \${misc:Depends}, freeswitch (= \${binary:Version}), freeswitch-mod-java (= \${binary:Version}), freeswitch-mod-lua (= \${binary:Version}), freeswitch-mod-perl (= \${binary:Version}), - freeswitch-mod-python (= \${binary:Version}), + freeswitch-mod-python3 (= \${binary:Version}), freeswitch-mod-yaml (= \${binary:Version}), freeswitch-mod-console (= \${binary:Version}), freeswitch-mod-logfile (= \${binary:Version}), @@ -922,7 +922,7 @@ Depends: \${misc:Depends}, freeswitch (= \${binary:Version}), freeswitch-mod-java-dbg (= \${binary:Version}), freeswitch-mod-lua-dbg (= \${binary:Version}), freeswitch-mod-perl-dbg (= \${binary:Version}), - freeswitch-mod-python-dbg (= \${binary:Version}), + freeswitch-mod-python3-dbg (= \${binary:Version}), freeswitch-mod-yaml-dbg (= \${binary:Version}), freeswitch-mod-console-dbg (= \${binary:Version}), freeswitch-mod-logfile-dbg (= \${binary:Version}), diff --git a/debian/control-modules b/debian/control-modules index 56772fa780..a3b53790a4 100644 --- a/debian/control-modules +++ b/debian/control-modules @@ -492,6 +492,7 @@ Description: Adds mod_verto. Adds mod_verto. Build-Depends: libperl-dev Build-Depends-Buster: libperl-dev, libgdbm-compat-dev +Build-Depends-Bullseye: libperl-dev, libgdbm-compat-dev ## mod/event_handlers @@ -665,11 +666,17 @@ Description: mod_perl Adds mod_perl. Build-Depends: libperl-dev Build-Depends-Buster: libperl-dev, libgdbm-compat-dev +Build-Depends-Bullseye: libperl-dev, libgdbm-compat-dev Module: languages/mod_python Description: mod_python Adds mod_python. -Build-Depends: python-dev +Build-Depends: python-dev | python-dev-is-python2 + +Module: languages/mod_python3 +Description: mod_python3 + Adds mod_python3. +Build-Depends: python3-dev Module: languages/mod_v8 Description: mod_v8 diff --git a/debian/freeswitch-mod-python.install.tmpl b/debian/freeswitch-mod-python.install.tmpl index 7f855822a1..9aef46eea1 100644 --- a/debian/freeswitch-mod-python.install.tmpl +++ b/debian/freeswitch-mod-python.install.tmpl @@ -1 +1 @@ -/usr/lib/python*/*-packages/freeswitch.py +/usr/lib/python2*/*-packages/freeswitch.py diff --git a/debian/freeswitch-mod-python3.install.tmpl b/debian/freeswitch-mod-python3.install.tmpl new file mode 100644 index 0000000000..9eae642fb6 --- /dev/null +++ b/debian/freeswitch-mod-python3.install.tmpl @@ -0,0 +1 @@ +/usr/lib/python3*/*-packages/freeswitch.py diff --git a/debian/rules b/debian/rules index 3cdf7b4ff3..c11f733e8c 100755 --- a/debian/rules +++ b/debian/rules @@ -73,7 +73,7 @@ override_dh_auto_clean: ./configure -C --enable-portable-binary --disable-dependency-tracking \ --host=$(DEB_HOST_GNU_TYPE) --build=$(DEB_BUILD_GNU_TYPE) \ --prefix=/usr --localstatedir=/var --sysconfdir=/etc \ - --with-gnu-ld --with-python --with-erlang --with-openssl \ + --with-gnu-ld --with-python --with-python3 --with-erlang --with-openssl \ --enable-core-odbc-support --enable-zrtp touch $@ @@ -85,6 +85,7 @@ override_dh_auto_configure: .stamp-configure make iksemel-dep make -j$(NJOBS) make -C libs/esl pymod + make -C libs/esl py3mod make -C libs/esl perlmod touch $@ @@ -99,6 +100,7 @@ override_dh_strip: override_dh_auto_install: dh_auto_install dh_auto_install -- -C libs/esl pymod-install + dh_auto_install -- -C libs/esl py3mod-install dh_auto_install -- -C libs/esl perlmod-install rm -f debian/tmp/usr/share/freeswitch/grammar/model/communicator/COPYING diff --git a/debian/util.sh b/debian/util.sh index 88cee7949b..6a5d8f27da 100755 --- a/debian/util.sh +++ b/debian/util.sh @@ -46,9 +46,9 @@ find_distro () { case "$1" in experimental) echo "sid";; unstable) echo "sid";; - testing) echo "buster";; - stable) echo "stretch";; - oldstable) echo "jessie";; + testing) echo "bullseye";; + stable) echo "buster";; + oldstable) echo "stretch";; *) echo "$1";; esac } @@ -56,9 +56,9 @@ find_distro () { find_suite () { case "$1" in sid) echo "unstable";; - buster) echo "testing";; - stretch) echo "stable";; - jessie) echo "oldstable";; + bullseye) echo "testing";; + buster) echo "stable";; + stretch) echo "oldstable";; *) echo "$1";; esac } diff --git a/freeswitch.spec b/freeswitch.spec index e4a0a178a3..19a7dd5516 100644 --- a/freeswitch.spec +++ b/freeswitch.spec @@ -140,7 +140,7 @@ BuildRequires: curl-devel >= 7.19 BuildRequires: gcc-c++ BuildRequires: libtool >= 1.5.17 BuildRequires: openssl-devel >= 1.0.1e -BuildRequires: sofia-sip-devel >= 1.13.5 +BuildRequires: sofia-sip-devel >= 1.13.6 BuildRequires: spandsp3-devel >= 3.0 BuildRequires: pcre-devel BuildRequires: speex-devel diff --git a/images/cluecon.jpg b/images/cluecon.jpg new file mode 100644 index 0000000000..a6e89751ea Binary files /dev/null and b/images/cluecon.jpg differ diff --git a/images/cluecon.png b/images/cluecon.png new file mode 100644 index 0000000000..7b0c4ced2b Binary files /dev/null and b/images/cluecon.png differ diff --git a/libs/.gitignore b/libs/.gitignore index 5a83438d92..355bae9a6d 100644 --- a/libs/.gitignore +++ b/libs/.gitignore @@ -793,4 +793,5 @@ mariadb-connector-c-*/ mariadb-connector-c-* /spandsp*/ /spandsp* -win32/spandsp/spandsp.h \ No newline at end of file +win32/spandsp/spandsp.h +win32/spandsp/win32 \ No newline at end of file diff --git a/libs/apr/tables/apr_hash.c b/libs/apr/tables/apr_hash.c index 5cac297af9..0e707601f5 100644 --- a/libs/apr/tables/apr_hash.c +++ b/libs/apr/tables/apr_hash.c @@ -28,6 +28,8 @@ #include #endif +#include /* assert() */ + #if APR_POOL_DEBUG && APR_HAVE_STDIO_H #include #endif @@ -433,6 +435,7 @@ APR_DECLARE(apr_hash_t *) apr_hash_merge(apr_pool_t *p, for (k = 0; k <= base->max; k++) { for (iter = base->array[k]; iter; iter = iter->next) { i = iter->hash & res->max; + assert(new_vals); new_vals[j].klen = iter->klen; new_vals[j].key = iter->key; new_vals[j].val = iter->val; diff --git a/libs/esl/Makefile.am b/libs/esl/Makefile.am index b946712311..695d9af841 100644 --- a/libs/esl/Makefile.am +++ b/libs/esl/Makefile.am @@ -54,6 +54,7 @@ reswig: swigclean $(MAKE) -C php reswig $(MAKE) -C lua reswig $(MAKE) -C python reswig + $(MAKE) -C python3 reswig $(MAKE) -C ruby reswig $(MAKE) -C java reswig $(MAKE) -C managed reswig @@ -63,6 +64,7 @@ swigclean: clean $(MAKE) -C php swigclean $(MAKE) -C lua swigclean $(MAKE) -C python swigclean + $(MAKE) -C python3 swigclean $(MAKE) -C ruby swigclean $(MAKE) -C java swigclean $(MAKE) -C managed swigclean @@ -77,7 +79,10 @@ luamod: $(MYLIB) $(MAKE) MYLIB="../$(MYLIB)" SOLINK="$(SOLINK)" CFLAGS="-I$(switch_srcdir)/libs/esl/src/include $(SWITCH_AM_CFLAGS)" CXXFLAGS="-I$(switch_srcdir)/libs/esl/src/include $(SWITCH_AM_CXXFLAGS)" CXX_CFLAGS="$(CXX_CFLAGS)" LUA_CFLAGS="$(LUA_CFLAGS)" LUA_LIBS="$(LUA_LIBS)" -C lua pymod: $(MYLIB) - $(MAKE) MYLIB="../$(MYLIB)" SOLINK="$(SOLINK)" CFLAGS="-I$(switch_srcdir)/libs/esl/src/include $(SWITCH_AM_CFLAGS)" CXXFLAGS="-I$(switch_srcdir)/libs/esl/src/include $(SWITCH_AM_CXXFLAGS)" CXX_CFLAGS="$(CXX_CFLAGS)" -C python + $(MAKE) PYTHON=$(PYTHON) MYLIB="../$(MYLIB)" SOLINK="$(SOLINK)" CFLAGS="-I$(switch_srcdir)/libs/esl/src/include $(SWITCH_AM_CFLAGS)" CXXFLAGS="-I$(switch_srcdir)/libs/esl/src/include $(SWITCH_AM_CXXFLAGS)" CXX_CFLAGS="$(CXX_CFLAGS)" -C python + +py3mod: $(MYLIB) + $(MAKE) PYTHON3=$(PYTHON3) MYLIB="../$(MYLIB)" SOLINK="$(SOLINK)" CFLAGS="-I$(switch_srcdir)/libs/esl/src/include $(SWITCH_AM_CFLAGS)" CXXFLAGS="-I$(switch_srcdir)/libs/esl/src/include $(SWITCH_AM_CXXFLAGS)" CXX_CFLAGS="$(CXX_CFLAGS)" -C python3 tclmod: $(MYLIB) $(MAKE) MYLIB="../$(MYLIB)" SOLINK="$(SOLINK)" CFLAGS="-I$(switch_srcdir)/libs/esl/src/include $(SWITCH_AM_CFLAGS)" CXXFLAGS="-I$(switch_srcdir)/libs/esl/src/include $(SWITCH_AM_CXXFLAGS)" CXX_CFLAGS="$(CXX_CFLAGS)" -C tcl @@ -98,9 +103,12 @@ phpmod-install: phpmod $(MAKE) -C php install pymod-install: pymod - $(MAKE) -C python install + $(MAKE) PYTHON=$(PYTHON) -C python install + +py3mod-install: py3mod + $(MAKE) PYTHON3=$(PYTHON3) -C python3 install rubymod-install: rubymod $(MAKE) -C ruby install -everymod: perlmod phpmod luamod pymod rubymod javamod managedmod +everymod: perlmod phpmod luamod pymod py3mod rubymod javamod managedmod diff --git a/libs/esl/python/Makefile b/libs/esl/python/Makefile index 71396dd4ba..824d3afe7f 100644 --- a/libs/esl/python/Makefile +++ b/libs/esl/python/Makefile @@ -1,6 +1,6 @@ -LOCAL_CFLAGS=`python ./python-config --includes` -LOCAL_LDFLAGS=`python ./python-config --ldflags` -SITE_DIR=$(DESTDIR)/`python -c "from distutils.sysconfig import get_python_lib; print get_python_lib(1)"` +LOCAL_CFLAGS=`$(PYTHON) ./python-config --includes` +LOCAL_LDFLAGS=`$(PYTHON) ./python-config --ldflags` +SITE_DIR=$(DESTDIR)/`$(PYTHON) -c "from distutils.sysconfig import get_python_lib; print get_python_lib(1)"` all: _ESL.so diff --git a/libs/esl/python3/ESL.py b/libs/esl/python3/ESL.py new file mode 100644 index 0000000000..cd9b7c4f3f --- /dev/null +++ b/libs/esl/python3/ESL.py @@ -0,0 +1,132 @@ +# This file was automatically generated by SWIG (http://www.swig.org). +# Version 3.0.2 +# +# Do not make changes to this file unless you know what you are doing--modify +# the SWIG interface file instead. + + + + + +from sys import version_info +if version_info >= (2,6,0): + def swig_import_helper(): + from os.path import dirname + import imp + fp = None + try: + fp, pathname, description = imp.find_module('_ESL', [dirname(__file__)]) + except ImportError: + import _ESL + return _ESL + if fp is not None: + try: + _mod = imp.load_module('_ESL', fp, pathname, description) + finally: + fp.close() + return _mod + _ESL = swig_import_helper() + del swig_import_helper +else: + import _ESL +del version_info +def _swig_setattr_nondynamic(self,class_type,name,value,static=1): + if (name == "thisown"): return self.this.own(value) + if (name == "this"): + if type(value).__name__ == 'SwigPyObject': + self.__dict__[name] = value + return + method = class_type.__swig_setmethods__.get(name,None) + if method: return method(self,value) + if (not static): + self.__dict__[name] = value + else: + raise AttributeError("You cannot add attributes to %s" % self) + +def _swig_setattr(self,class_type,name,value): + return _swig_setattr_nondynamic(self,class_type,name,value,0) + +def _swig_getattr(self,class_type,name): + if (name == "thisown"): return self.this.own() + method = class_type.__swig_getmethods__.get(name,None) + if method: return method(self) + raise AttributeError(name) + +def _swig_repr(self): + try: strthis = "proxy of " + self.this.__repr__() + except: strthis = "" + return "<%s.%s; %s >" % (self.__class__.__module__, self.__class__.__name__, strthis,) + +class ESLevent: + __swig_setmethods__ = {} + __setattr__ = lambda self, name, value: _swig_setattr(self, ESLevent, name, value) + __swig_getmethods__ = {} + __getattr__ = lambda self, name: _swig_getattr(self, ESLevent, name) + __repr__ = _swig_repr + __swig_setmethods__["event"] = _ESL.ESLevent_event_set + __swig_getmethods__["event"] = _ESL.ESLevent_event_get + __swig_setmethods__["serialized_string"] = _ESL.ESLevent_serialized_string_set + __swig_getmethods__["serialized_string"] = _ESL.ESLevent_serialized_string_get + __swig_setmethods__["mine"] = _ESL.ESLevent_mine_set + __swig_getmethods__["mine"] = _ESL.ESLevent_mine_get + def __init__(self, *args): + this = _ESL.new_ESLevent(*args) + try: self.this.append(this) + except: self.this = this + __swig_destroy__ = _ESL.delete_ESLevent + __del__ = lambda self : None; + def serialize(self, format=None): return _ESL.ESLevent_serialize(self, format) + def setPriority(self, *args): return _ESL.ESLevent_setPriority(self, *args) + def getHeader(self, *args): return _ESL.ESLevent_getHeader(self, *args) + def getBody(self): return _ESL.ESLevent_getBody(self) + def getType(self): return _ESL.ESLevent_getType(self) + def addBody(self, *args): return _ESL.ESLevent_addBody(self, *args) + def addHeader(self, *args): return _ESL.ESLevent_addHeader(self, *args) + def pushHeader(self, *args): return _ESL.ESLevent_pushHeader(self, *args) + def unshiftHeader(self, *args): return _ESL.ESLevent_unshiftHeader(self, *args) + def delHeader(self, *args): return _ESL.ESLevent_delHeader(self, *args) + def firstHeader(self): return _ESL.ESLevent_firstHeader(self) + def nextHeader(self): return _ESL.ESLevent_nextHeader(self) +ESLevent_swigregister = _ESL.ESLevent_swigregister +ESLevent_swigregister(ESLevent) + +class ESLconnection: + __swig_setmethods__ = {} + __setattr__ = lambda self, name, value: _swig_setattr(self, ESLconnection, name, value) + __swig_getmethods__ = {} + __getattr__ = lambda self, name: _swig_getattr(self, ESLconnection, name) + __repr__ = _swig_repr + def __init__(self, *args): + this = _ESL.new_ESLconnection(*args) + try: self.this.append(this) + except: self.this = this + __swig_destroy__ = _ESL.delete_ESLconnection + __del__ = lambda self : None; + def socketDescriptor(self): return _ESL.ESLconnection_socketDescriptor(self) + def connected(self): return _ESL.ESLconnection_connected(self) + def getInfo(self): return _ESL.ESLconnection_getInfo(self) + def send(self, *args): return _ESL.ESLconnection_send(self, *args) + def sendRecv(self, *args): return _ESL.ESLconnection_sendRecv(self, *args) + def api(self, *args): return _ESL.ESLconnection_api(self, *args) + def bgapi(self, *args): return _ESL.ESLconnection_bgapi(self, *args) + def sendEvent(self, *args): return _ESL.ESLconnection_sendEvent(self, *args) + def sendMSG(self, *args): return _ESL.ESLconnection_sendMSG(self, *args) + def recvEvent(self): return _ESL.ESLconnection_recvEvent(self) + def recvEventTimed(self, *args): return _ESL.ESLconnection_recvEventTimed(self, *args) + def filter(self, *args): return _ESL.ESLconnection_filter(self, *args) + def events(self, *args): return _ESL.ESLconnection_events(self, *args) + def execute(self, *args): return _ESL.ESLconnection_execute(self, *args) + def executeAsync(self, *args): return _ESL.ESLconnection_executeAsync(self, *args) + def setAsyncExecute(self, *args): return _ESL.ESLconnection_setAsyncExecute(self, *args) + def setEventLock(self, *args): return _ESL.ESLconnection_setEventLock(self, *args) + def disconnect(self): return _ESL.ESLconnection_disconnect(self) +ESLconnection_swigregister = _ESL.ESLconnection_swigregister +ESLconnection_swigregister(ESLconnection) + + +def eslSetLogLevel(*args): + return _ESL.eslSetLogLevel(*args) +eslSetLogLevel = _ESL.eslSetLogLevel +# This file is compatible with both classic and new-style classes. + + diff --git a/libs/esl/python3/Makefile b/libs/esl/python3/Makefile new file mode 100644 index 0000000000..1c838534fd --- /dev/null +++ b/libs/esl/python3/Makefile @@ -0,0 +1,28 @@ +LOCAL_CFLAGS=`$(PYTHON3) ./python-config --includes` +LOCAL_LDFLAGS=`$(PYTHON3) ./python-config --ldflags` +SITE_DIR=$(DESTDIR)/`$(PYTHON3) -c "from distutils.sysconfig import get_python_lib; print (get_python_lib(1))"` + +all: _ESL.so + +esl_wrap.cpp: + swig3.0 -module ESL -classic -python -c++ -DMULTIPLICITY -threads -I../src/include -o esl_wrap.cpp ../ESL.i + +esl_wrap.o: esl_wrap.cpp + $(CXX) $(CXX_CFLAGS) $(CXXFLAGS) $(LOCAL_CFLAGS) -c esl_wrap.cpp -o esl_wrap.o + +_ESL.so: esl_wrap.o + $(CXX) $(SOLINK) esl_wrap.o $(MYLIB) $(LOCAL_LDFLAGS) -o _ESL.so -L. $(LIBS) + +install: _ESL.so + mkdir -p $(SITE_DIR) + install -m 755 _ESL.so $(SITE_DIR) + install -m 755 ESL.py $(SITE_DIR) + +clean: + rm -f *.o *.so *~ + +swigclean: + rm -f esl_wrap.* ESL.so + +reswig: swigclean esl_wrap.cpp + diff --git a/libs/esl/python3/esl_wrap.cpp b/libs/esl/python3/esl_wrap.cpp new file mode 100644 index 0000000000..b67be5488a --- /dev/null +++ b/libs/esl/python3/esl_wrap.cpp @@ -0,0 +1,6128 @@ +/* ---------------------------------------------------------------------------- + * This file was automatically generated by SWIG (http://www.swig.org). + * Version 3.0.2 + * + * This file is not intended to be easily readable and contains a number of + * coding conventions designed to improve portability and efficiency. Do not make + * changes to this file unless you know what you are doing--modify the SWIG + * interface file instead. + * ----------------------------------------------------------------------------- */ + +#define SWIGPYTHON +#define SWIG_PYTHON_THREADS +#define SWIG_PYTHON_DIRECTOR_NO_VTABLE +#define SWIG_PYTHON_CLASSIC + + +#ifdef __cplusplus +/* SwigValueWrapper is described in swig.swg */ +template class SwigValueWrapper { + struct SwigMovePointer { + T *ptr; + SwigMovePointer(T *p) : ptr(p) { } + ~SwigMovePointer() { delete ptr; } + SwigMovePointer& operator=(SwigMovePointer& rhs) { T* oldptr = ptr; ptr = 0; delete oldptr; ptr = rhs.ptr; rhs.ptr = 0; return *this; } + } pointer; + SwigValueWrapper& operator=(const SwigValueWrapper& rhs); + SwigValueWrapper(const SwigValueWrapper& rhs); +public: + SwigValueWrapper() : pointer(0) { } + SwigValueWrapper& operator=(const T& t) { SwigMovePointer tmp(new T(t)); pointer = tmp; return *this; } + operator T&() const { return *pointer.ptr; } + T *operator&() { return pointer.ptr; } +}; + +template T SwigValueInit() { + return T(); +} +#endif + +/* ----------------------------------------------------------------------------- + * This section contains generic SWIG labels for method/variable + * declarations/attributes, and other compiler dependent labels. + * ----------------------------------------------------------------------------- */ + +/* template workaround for compilers that cannot correctly implement the C++ standard */ +#ifndef SWIGTEMPLATEDISAMBIGUATOR +# if defined(__SUNPRO_CC) && (__SUNPRO_CC <= 0x560) +# define SWIGTEMPLATEDISAMBIGUATOR template +# elif defined(__HP_aCC) +/* Needed even with `aCC -AA' when `aCC -V' reports HP ANSI C++ B3910B A.03.55 */ +/* If we find a maximum version that requires this, the test would be __HP_aCC <= 35500 for A.03.55 */ +# define SWIGTEMPLATEDISAMBIGUATOR template +# else +# define SWIGTEMPLATEDISAMBIGUATOR +# endif +#endif + +/* inline attribute */ +#ifndef SWIGINLINE +# if defined(__cplusplus) || (defined(__GNUC__) && !defined(__STRICT_ANSI__)) +# define SWIGINLINE inline +# else +# define SWIGINLINE +# endif +#endif + +/* attribute recognised by some compilers to avoid 'unused' warnings */ +#ifndef SWIGUNUSED +# if defined(__GNUC__) +# if !(defined(__cplusplus)) || (__GNUC__ > 3 || (__GNUC__ == 3 && __GNUC_MINOR__ >= 4)) +# define SWIGUNUSED __attribute__ ((__unused__)) +# else +# define SWIGUNUSED +# endif +# elif defined(__ICC) +# define SWIGUNUSED __attribute__ ((__unused__)) +# else +# define SWIGUNUSED +# endif +#endif + +#ifndef SWIG_MSC_UNSUPPRESS_4505 +# if defined(_MSC_VER) +# pragma warning(disable : 4505) /* unreferenced local function has been removed */ +# endif +#endif + +#ifndef SWIGUNUSEDPARM +# ifdef __cplusplus +# define SWIGUNUSEDPARM(p) +# else +# define SWIGUNUSEDPARM(p) p SWIGUNUSED +# endif +#endif + +/* internal SWIG method */ +#ifndef SWIGINTERN +# define SWIGINTERN static SWIGUNUSED +#endif + +/* internal inline SWIG method */ +#ifndef SWIGINTERNINLINE +# define SWIGINTERNINLINE SWIGINTERN SWIGINLINE +#endif + +/* exporting methods */ +#if (__GNUC__ >= 4) || (__GNUC__ == 3 && __GNUC_MINOR__ >= 4) +# ifndef GCC_HASCLASSVISIBILITY +# define GCC_HASCLASSVISIBILITY +# endif +#endif + +#ifndef SWIGEXPORT +# if defined(_WIN32) || defined(__WIN32__) || defined(__CYGWIN__) +# if defined(STATIC_LINKED) +# define SWIGEXPORT +# else +# define SWIGEXPORT __declspec(dllexport) +# endif +# else +# if defined(__GNUC__) && defined(GCC_HASCLASSVISIBILITY) +# define SWIGEXPORT __attribute__ ((visibility("default"))) +# else +# define SWIGEXPORT +# endif +# endif +#endif + +/* calling conventions for Windows */ +#ifndef SWIGSTDCALL +# if defined(_WIN32) || defined(__WIN32__) || defined(__CYGWIN__) +# define SWIGSTDCALL __stdcall +# else +# define SWIGSTDCALL +# endif +#endif + +/* Deal with Microsoft's attempt at deprecating C standard runtime functions */ +#if !defined(SWIG_NO_CRT_SECURE_NO_DEPRECATE) && defined(_MSC_VER) && !defined(_CRT_SECURE_NO_DEPRECATE) +# define _CRT_SECURE_NO_DEPRECATE +#endif + +/* Deal with Microsoft's attempt at deprecating methods in the standard C++ library */ +#if !defined(SWIG_NO_SCL_SECURE_NO_DEPRECATE) && defined(_MSC_VER) && !defined(_SCL_SECURE_NO_DEPRECATE) +# define _SCL_SECURE_NO_DEPRECATE +#endif + + + +#if defined(_DEBUG) && defined(SWIG_PYTHON_INTERPRETER_NO_DEBUG) +/* Use debug wrappers with the Python release dll */ +# undef _DEBUG +# include +# define _DEBUG +#else +# include +#endif + +/* ----------------------------------------------------------------------------- + * swigrun.swg + * + * This file contains generic C API SWIG runtime support for pointer + * type checking. + * ----------------------------------------------------------------------------- */ + +/* This should only be incremented when either the layout of swig_type_info changes, + or for whatever reason, the runtime changes incompatibly */ +#define SWIG_RUNTIME_VERSION "4" + +/* define SWIG_TYPE_TABLE_NAME as "SWIG_TYPE_TABLE" */ +#ifdef SWIG_TYPE_TABLE +# define SWIG_QUOTE_STRING(x) #x +# define SWIG_EXPAND_AND_QUOTE_STRING(x) SWIG_QUOTE_STRING(x) +# define SWIG_TYPE_TABLE_NAME SWIG_EXPAND_AND_QUOTE_STRING(SWIG_TYPE_TABLE) +#else +# define SWIG_TYPE_TABLE_NAME +#endif + +/* + You can use the SWIGRUNTIME and SWIGRUNTIMEINLINE macros for + creating a static or dynamic library from the SWIG runtime code. + In 99.9% of the cases, SWIG just needs to declare them as 'static'. + + But only do this if strictly necessary, ie, if you have problems + with your compiler or suchlike. +*/ + +#ifndef SWIGRUNTIME +# define SWIGRUNTIME SWIGINTERN +#endif + +#ifndef SWIGRUNTIMEINLINE +# define SWIGRUNTIMEINLINE SWIGRUNTIME SWIGINLINE +#endif + +/* Generic buffer size */ +#ifndef SWIG_BUFFER_SIZE +# define SWIG_BUFFER_SIZE 1024 +#endif + +/* Flags for pointer conversions */ +#define SWIG_POINTER_DISOWN 0x1 +#define SWIG_CAST_NEW_MEMORY 0x2 + +/* Flags for new pointer objects */ +#define SWIG_POINTER_OWN 0x1 + + +/* + Flags/methods for returning states. + + The SWIG conversion methods, as ConvertPtr, return an integer + that tells if the conversion was successful or not. And if not, + an error code can be returned (see swigerrors.swg for the codes). + + Use the following macros/flags to set or process the returning + states. + + In old versions of SWIG, code such as the following was usually written: + + if (SWIG_ConvertPtr(obj,vptr,ty.flags) != -1) { + // success code + } else { + //fail code + } + + Now you can be more explicit: + + int res = SWIG_ConvertPtr(obj,vptr,ty.flags); + if (SWIG_IsOK(res)) { + // success code + } else { + // fail code + } + + which is the same really, but now you can also do + + Type *ptr; + int res = SWIG_ConvertPtr(obj,(void **)(&ptr),ty.flags); + if (SWIG_IsOK(res)) { + // success code + if (SWIG_IsNewObj(res) { + ... + delete *ptr; + } else { + ... + } + } else { + // fail code + } + + I.e., now SWIG_ConvertPtr can return new objects and you can + identify the case and take care of the deallocation. Of course that + also requires SWIG_ConvertPtr to return new result values, such as + + int SWIG_ConvertPtr(obj, ptr,...) { + if () { + if () { + *ptr = ; + return SWIG_NEWOBJ; + } else { + *ptr = ; + return SWIG_OLDOBJ; + } + } else { + return SWIG_BADOBJ; + } + } + + Of course, returning the plain '0(success)/-1(fail)' still works, but you can be + more explicit by returning SWIG_BADOBJ, SWIG_ERROR or any of the + SWIG errors code. + + Finally, if the SWIG_CASTRANK_MODE is enabled, the result code + allows to return the 'cast rank', for example, if you have this + + int food(double) + int fooi(int); + + and you call + + food(1) // cast rank '1' (1 -> 1.0) + fooi(1) // cast rank '0' + + just use the SWIG_AddCast()/SWIG_CheckState() +*/ + +#define SWIG_OK (0) +#define SWIG_ERROR (-1) +#define SWIG_IsOK(r) (r >= 0) +#define SWIG_ArgError(r) ((r != SWIG_ERROR) ? r : SWIG_TypeError) + +/* The CastRankLimit says how many bits are used for the cast rank */ +#define SWIG_CASTRANKLIMIT (1 << 8) +/* The NewMask denotes the object was created (using new/malloc) */ +#define SWIG_NEWOBJMASK (SWIG_CASTRANKLIMIT << 1) +/* The TmpMask is for in/out typemaps that use temporal objects */ +#define SWIG_TMPOBJMASK (SWIG_NEWOBJMASK << 1) +/* Simple returning values */ +#define SWIG_BADOBJ (SWIG_ERROR) +#define SWIG_OLDOBJ (SWIG_OK) +#define SWIG_NEWOBJ (SWIG_OK | SWIG_NEWOBJMASK) +#define SWIG_TMPOBJ (SWIG_OK | SWIG_TMPOBJMASK) +/* Check, add and del mask methods */ +#define SWIG_AddNewMask(r) (SWIG_IsOK(r) ? (r | SWIG_NEWOBJMASK) : r) +#define SWIG_DelNewMask(r) (SWIG_IsOK(r) ? (r & ~SWIG_NEWOBJMASK) : r) +#define SWIG_IsNewObj(r) (SWIG_IsOK(r) && (r & SWIG_NEWOBJMASK)) +#define SWIG_AddTmpMask(r) (SWIG_IsOK(r) ? (r | SWIG_TMPOBJMASK) : r) +#define SWIG_DelTmpMask(r) (SWIG_IsOK(r) ? (r & ~SWIG_TMPOBJMASK) : r) +#define SWIG_IsTmpObj(r) (SWIG_IsOK(r) && (r & SWIG_TMPOBJMASK)) + +/* Cast-Rank Mode */ +#if defined(SWIG_CASTRANK_MODE) +# ifndef SWIG_TypeRank +# define SWIG_TypeRank unsigned long +# endif +# ifndef SWIG_MAXCASTRANK /* Default cast allowed */ +# define SWIG_MAXCASTRANK (2) +# endif +# define SWIG_CASTRANKMASK ((SWIG_CASTRANKLIMIT) -1) +# define SWIG_CastRank(r) (r & SWIG_CASTRANKMASK) +SWIGINTERNINLINE int SWIG_AddCast(int r) { + return SWIG_IsOK(r) ? ((SWIG_CastRank(r) < SWIG_MAXCASTRANK) ? (r + 1) : SWIG_ERROR) : r; +} +SWIGINTERNINLINE int SWIG_CheckState(int r) { + return SWIG_IsOK(r) ? SWIG_CastRank(r) + 1 : 0; +} +#else /* no cast-rank mode */ +# define SWIG_AddCast(r) (r) +# define SWIG_CheckState(r) (SWIG_IsOK(r) ? 1 : 0) +#endif + + +#include + +#ifdef __cplusplus +extern "C" { +#endif + +typedef void *(*swig_converter_func)(void *, int *); +typedef struct swig_type_info *(*swig_dycast_func)(void **); + +/* Structure to store information on one type */ +typedef struct swig_type_info { + const char *name; /* mangled name of this type */ + const char *str; /* human readable name of this type */ + swig_dycast_func dcast; /* dynamic cast function down a hierarchy */ + struct swig_cast_info *cast; /* linked list of types that can cast into this type */ + void *clientdata; /* language specific type data */ + int owndata; /* flag if the structure owns the clientdata */ +} swig_type_info; + +/* Structure to store a type and conversion function used for casting */ +typedef struct swig_cast_info { + swig_type_info *type; /* pointer to type that is equivalent to this type */ + swig_converter_func converter; /* function to cast the void pointers */ + struct swig_cast_info *next; /* pointer to next cast in linked list */ + struct swig_cast_info *prev; /* pointer to the previous cast */ +} swig_cast_info; + +/* Structure used to store module information + * Each module generates one structure like this, and the runtime collects + * all of these structures and stores them in a circularly linked list.*/ +typedef struct swig_module_info { + swig_type_info **types; /* Array of pointers to swig_type_info structures that are in this module */ + size_t size; /* Number of types in this module */ + struct swig_module_info *next; /* Pointer to next element in circularly linked list */ + swig_type_info **type_initial; /* Array of initially generated type structures */ + swig_cast_info **cast_initial; /* Array of initially generated casting structures */ + void *clientdata; /* Language specific module data */ +} swig_module_info; + +/* + Compare two type names skipping the space characters, therefore + "char*" == "char *" and "Class" == "Class", etc. + + Return 0 when the two name types are equivalent, as in + strncmp, but skipping ' '. +*/ +SWIGRUNTIME int +SWIG_TypeNameComp(const char *f1, const char *l1, + const char *f2, const char *l2) { + for (;(f1 != l1) && (f2 != l2); ++f1, ++f2) { + while ((*f1 == ' ') && (f1 != l1)) ++f1; + while ((*f2 == ' ') && (f2 != l2)) ++f2; + if (*f1 != *f2) return (*f1 > *f2) ? 1 : -1; + } + return (int)((l1 - f1) - (l2 - f2)); +} + +/* + Check type equivalence in a name list like ||... + Return 0 if equal, -1 if nb < tb, 1 if nb > tb +*/ +SWIGRUNTIME int +SWIG_TypeCmp(const char *nb, const char *tb) { + int equiv = 1; + const char* te = tb + strlen(tb); + const char* ne = nb; + while (equiv != 0 && *ne) { + for (nb = ne; *ne; ++ne) { + if (*ne == '|') break; + } + equiv = SWIG_TypeNameComp(nb, ne, tb, te); + if (*ne) ++ne; + } + return equiv; +} + +/* + Check type equivalence in a name list like ||... + Return 0 if not equal, 1 if equal +*/ +SWIGRUNTIME int +SWIG_TypeEquiv(const char *nb, const char *tb) { + return SWIG_TypeCmp(nb, tb) == 0 ? 1 : 0; +} + +/* + Check the typename +*/ +SWIGRUNTIME swig_cast_info * +SWIG_TypeCheck(const char *c, swig_type_info *ty) { + if (ty) { + swig_cast_info *iter = ty->cast; + while (iter) { + if (strcmp(iter->type->name, c) == 0) { + if (iter == ty->cast) + return iter; + /* Move iter to the top of the linked list */ + iter->prev->next = iter->next; + if (iter->next) + iter->next->prev = iter->prev; + iter->next = ty->cast; + iter->prev = 0; + if (ty->cast) ty->cast->prev = iter; + ty->cast = iter; + return iter; + } + iter = iter->next; + } + } + return 0; +} + +/* + Identical to SWIG_TypeCheck, except strcmp is replaced with a pointer comparison +*/ +SWIGRUNTIME swig_cast_info * +SWIG_TypeCheckStruct(swig_type_info *from, swig_type_info *ty) { + if (ty) { + swig_cast_info *iter = ty->cast; + while (iter) { + if (iter->type == from) { + if (iter == ty->cast) + return iter; + /* Move iter to the top of the linked list */ + iter->prev->next = iter->next; + if (iter->next) + iter->next->prev = iter->prev; + iter->next = ty->cast; + iter->prev = 0; + if (ty->cast) ty->cast->prev = iter; + ty->cast = iter; + return iter; + } + iter = iter->next; + } + } + return 0; +} + +/* + Cast a pointer up an inheritance hierarchy +*/ +SWIGRUNTIMEINLINE void * +SWIG_TypeCast(swig_cast_info *ty, void *ptr, int *newmemory) { + return ((!ty) || (!ty->converter)) ? ptr : (*ty->converter)(ptr, newmemory); +} + +/* + Dynamic pointer casting. Down an inheritance hierarchy +*/ +SWIGRUNTIME swig_type_info * +SWIG_TypeDynamicCast(swig_type_info *ty, void **ptr) { + swig_type_info *lastty = ty; + if (!ty || !ty->dcast) return ty; + while (ty && (ty->dcast)) { + ty = (*ty->dcast)(ptr); + if (ty) lastty = ty; + } + return lastty; +} + +/* + Return the name associated with this type +*/ +SWIGRUNTIMEINLINE const char * +SWIG_TypeName(const swig_type_info *ty) { + return ty->name; +} + +/* + Return the pretty name associated with this type, + that is an unmangled type name in a form presentable to the user. +*/ +SWIGRUNTIME const char * +SWIG_TypePrettyName(const swig_type_info *type) { + /* The "str" field contains the equivalent pretty names of the + type, separated by vertical-bar characters. We choose + to print the last name, as it is often (?) the most + specific. */ + if (!type) return NULL; + if (type->str != NULL) { + const char *last_name = type->str; + const char *s; + for (s = type->str; *s; s++) + if (*s == '|') last_name = s+1; + return last_name; + } + else + return type->name; +} + +/* + Set the clientdata field for a type +*/ +SWIGRUNTIME void +SWIG_TypeClientData(swig_type_info *ti, void *clientdata) { + swig_cast_info *cast = ti->cast; + /* if (ti->clientdata == clientdata) return; */ + ti->clientdata = clientdata; + + while (cast) { + if (!cast->converter) { + swig_type_info *tc = cast->type; + if (!tc->clientdata) { + SWIG_TypeClientData(tc, clientdata); + } + } + cast = cast->next; + } +} +SWIGRUNTIME void +SWIG_TypeNewClientData(swig_type_info *ti, void *clientdata) { + SWIG_TypeClientData(ti, clientdata); + ti->owndata = 1; +} + +/* + Search for a swig_type_info structure only by mangled name + Search is a O(log #types) + + We start searching at module start, and finish searching when start == end. + Note: if start == end at the beginning of the function, we go all the way around + the circular list. +*/ +SWIGRUNTIME swig_type_info * +SWIG_MangledTypeQueryModule(swig_module_info *start, + swig_module_info *end, + const char *name) { + swig_module_info *iter = start; + do { + if (iter->size) { + size_t l = 0; + size_t r = iter->size - 1; + do { + /* since l+r >= 0, we can (>> 1) instead (/ 2) */ + size_t i = (l + r) >> 1; + const char *iname = iter->types[i]->name; + if (iname) { + int compare = strcmp(name, iname); + if (compare == 0) { + return iter->types[i]; + } else if (compare < 0) { + if (i) { + r = i - 1; + } else { + break; + } + } else if (compare > 0) { + l = i + 1; + } + } else { + break; /* should never happen */ + } + } while (l <= r); + } + iter = iter->next; + } while (iter != end); + return 0; +} + +/* + Search for a swig_type_info structure for either a mangled name or a human readable name. + It first searches the mangled names of the types, which is a O(log #types) + If a type is not found it then searches the human readable names, which is O(#types). + + We start searching at module start, and finish searching when start == end. + Note: if start == end at the beginning of the function, we go all the way around + the circular list. +*/ +SWIGRUNTIME swig_type_info * +SWIG_TypeQueryModule(swig_module_info *start, + swig_module_info *end, + const char *name) { + /* STEP 1: Search the name field using binary search */ + swig_type_info *ret = SWIG_MangledTypeQueryModule(start, end, name); + if (ret) { + return ret; + } else { + /* STEP 2: If the type hasn't been found, do a complete search + of the str field (the human readable name) */ + swig_module_info *iter = start; + do { + size_t i = 0; + for (; i < iter->size; ++i) { + if (iter->types[i]->str && (SWIG_TypeEquiv(iter->types[i]->str, name))) + return iter->types[i]; + } + iter = iter->next; + } while (iter != end); + } + + /* neither found a match */ + return 0; +} + +/* + Pack binary data into a string +*/ +SWIGRUNTIME char * +SWIG_PackData(char *c, void *ptr, size_t sz) { + static const char hex[17] = "0123456789abcdef"; + const unsigned char *u = (unsigned char *) ptr; + const unsigned char *eu = u + sz; + for (; u != eu; ++u) { + unsigned char uu = *u; + *(c++) = hex[(uu & 0xf0) >> 4]; + *(c++) = hex[uu & 0xf]; + } + return c; +} + +/* + Unpack binary data from a string +*/ +SWIGRUNTIME const char * +SWIG_UnpackData(const char *c, void *ptr, size_t sz) { + unsigned char *u = (unsigned char *) ptr; + const unsigned char *eu = u + sz; + for (; u != eu; ++u) { + char d = *(c++); + unsigned char uu; + if ((d >= '0') && (d <= '9')) + uu = ((d - '0') << 4); + else if ((d >= 'a') && (d <= 'f')) + uu = ((d - ('a'-10)) << 4); + else + return (char *) 0; + d = *(c++); + if ((d >= '0') && (d <= '9')) + uu |= (d - '0'); + else if ((d >= 'a') && (d <= 'f')) + uu |= (d - ('a'-10)); + else + return (char *) 0; + *u = uu; + } + return c; +} + +/* + Pack 'void *' into a string buffer. +*/ +SWIGRUNTIME char * +SWIG_PackVoidPtr(char *buff, void *ptr, const char *name, size_t bsz) { + char *r = buff; + if ((2*sizeof(void *) + 2) > bsz) return 0; + *(r++) = '_'; + r = SWIG_PackData(r,&ptr,sizeof(void *)); + if (strlen(name) + 1 > (bsz - (r - buff))) return 0; + strcpy(r,name); + return buff; +} + +SWIGRUNTIME const char * +SWIG_UnpackVoidPtr(const char *c, void **ptr, const char *name) { + if (*c != '_') { + if (strcmp(c,"NULL") == 0) { + *ptr = (void *) 0; + return name; + } else { + return 0; + } + } + return SWIG_UnpackData(++c,ptr,sizeof(void *)); +} + +SWIGRUNTIME char * +SWIG_PackDataName(char *buff, void *ptr, size_t sz, const char *name, size_t bsz) { + char *r = buff; + size_t lname = (name ? strlen(name) : 0); + if ((2*sz + 2 + lname) > bsz) return 0; + *(r++) = '_'; + r = SWIG_PackData(r,ptr,sz); + if (lname) { + strncpy(r,name,lname+1); + } else { + *r = 0; + } + return buff; +} + +SWIGRUNTIME const char * +SWIG_UnpackDataName(const char *c, void *ptr, size_t sz, const char *name) { + if (*c != '_') { + if (strcmp(c,"NULL") == 0) { + memset(ptr,0,sz); + return name; + } else { + return 0; + } + } + return SWIG_UnpackData(++c,ptr,sz); +} + +#ifdef __cplusplus +} +#endif + +/* Errors in SWIG */ +#define SWIG_UnknownError -1 +#define SWIG_IOError -2 +#define SWIG_RuntimeError -3 +#define SWIG_IndexError -4 +#define SWIG_TypeError -5 +#define SWIG_DivisionByZero -6 +#define SWIG_OverflowError -7 +#define SWIG_SyntaxError -8 +#define SWIG_ValueError -9 +#define SWIG_SystemError -10 +#define SWIG_AttributeError -11 +#define SWIG_MemoryError -12 +#define SWIG_NullReferenceError -13 + + + +/* Compatibility macros for Python 3 */ +#if PY_VERSION_HEX >= 0x03000000 + +#define PyClass_Check(obj) PyObject_IsInstance(obj, (PyObject *)&PyType_Type) +#define PyInt_Check(x) PyLong_Check(x) +#define PyInt_AsLong(x) PyLong_AsLong(x) +#define PyInt_FromLong(x) PyLong_FromLong(x) +#define PyInt_FromSize_t(x) PyLong_FromSize_t(x) +#define PyString_Check(name) PyBytes_Check(name) +#define PyString_FromString(x) PyUnicode_FromString(x) +#define PyString_Format(fmt, args) PyUnicode_Format(fmt, args) +#define PyString_AsString(str) PyBytes_AsString(str) +#define PyString_Size(str) PyBytes_Size(str) +#define PyString_InternFromString(key) PyUnicode_InternFromString(key) +#define Py_TPFLAGS_HAVE_CLASS Py_TPFLAGS_BASETYPE +#define PyString_AS_STRING(x) PyUnicode_AS_STRING(x) +#define _PyLong_FromSsize_t(x) PyLong_FromSsize_t(x) + +#endif + +#ifndef Py_TYPE +# define Py_TYPE(op) ((op)->ob_type) +#endif + +/* SWIG APIs for compatibility of both Python 2 & 3 */ + +#if PY_VERSION_HEX >= 0x03000000 +# define SWIG_Python_str_FromFormat PyUnicode_FromFormat +#else +# define SWIG_Python_str_FromFormat PyString_FromFormat +#endif + + +/* Warning: This function will allocate a new string in Python 3, + * so please call SWIG_Python_str_DelForPy3(x) to free the space. + */ +SWIGINTERN char* +SWIG_Python_str_AsChar(PyObject *str) +{ +#if PY_VERSION_HEX >= 0x03000000 + char *cstr; + char *newstr; + Py_ssize_t len; + str = PyUnicode_AsUTF8String(str); + PyBytes_AsStringAndSize(str, &cstr, &len); + newstr = (char *) malloc(len+1); + memcpy(newstr, cstr, len+1); + Py_XDECREF(str); + return newstr; +#else + return PyString_AsString(str); +#endif +} + +#if PY_VERSION_HEX >= 0x03000000 +# define SWIG_Python_str_DelForPy3(x) free( (void*) (x) ) +#else +# define SWIG_Python_str_DelForPy3(x) +#endif + + +SWIGINTERN PyObject* +SWIG_Python_str_FromChar(const char *c) +{ +#if PY_VERSION_HEX >= 0x03000000 + return PyUnicode_FromString(c); +#else + return PyString_FromString(c); +#endif +} + +/* Add PyOS_snprintf for old Pythons */ +#if PY_VERSION_HEX < 0x02020000 +# if defined(_MSC_VER) || defined(__BORLANDC__) || defined(_WATCOM) +# define PyOS_snprintf _snprintf +# else +# define PyOS_snprintf snprintf +# endif +#endif + +/* A crude PyString_FromFormat implementation for old Pythons */ +#if PY_VERSION_HEX < 0x02020000 + +#ifndef SWIG_PYBUFFER_SIZE +# define SWIG_PYBUFFER_SIZE 1024 +#endif + +static PyObject * +PyString_FromFormat(const char *fmt, ...) { + va_list ap; + char buf[SWIG_PYBUFFER_SIZE * 2]; + int res; + va_start(ap, fmt); + res = vsnprintf(buf, sizeof(buf), fmt, ap); + va_end(ap); + return (res < 0 || res >= (int)sizeof(buf)) ? 0 : PyString_FromString(buf); +} +#endif + +/* Add PyObject_Del for old Pythons */ +#if PY_VERSION_HEX < 0x01060000 +# define PyObject_Del(op) PyMem_DEL((op)) +#endif +#ifndef PyObject_DEL +# define PyObject_DEL PyObject_Del +#endif + +/* A crude PyExc_StopIteration exception for old Pythons */ +#if PY_VERSION_HEX < 0x02020000 +# ifndef PyExc_StopIteration +# define PyExc_StopIteration PyExc_RuntimeError +# endif +# ifndef PyObject_GenericGetAttr +# define PyObject_GenericGetAttr 0 +# endif +#endif + +/* Py_NotImplemented is defined in 2.1 and up. */ +#if PY_VERSION_HEX < 0x02010000 +# ifndef Py_NotImplemented +# define Py_NotImplemented PyExc_RuntimeError +# endif +#endif + +/* A crude PyString_AsStringAndSize implementation for old Pythons */ +#if PY_VERSION_HEX < 0x02010000 +# ifndef PyString_AsStringAndSize +# define PyString_AsStringAndSize(obj, s, len) {*s = PyString_AsString(obj); *len = *s ? strlen(*s) : 0;} +# endif +#endif + +/* PySequence_Size for old Pythons */ +#if PY_VERSION_HEX < 0x02000000 +# ifndef PySequence_Size +# define PySequence_Size PySequence_Length +# endif +#endif + +/* PyBool_FromLong for old Pythons */ +#if PY_VERSION_HEX < 0x02030000 +static +PyObject *PyBool_FromLong(long ok) +{ + PyObject *result = ok ? Py_True : Py_False; + Py_INCREF(result); + return result; +} +#endif + +/* Py_ssize_t for old Pythons */ +/* This code is as recommended by: */ +/* http://www.python.org/dev/peps/pep-0353/#conversion-guidelines */ +#if PY_VERSION_HEX < 0x02050000 && !defined(PY_SSIZE_T_MIN) +typedef int Py_ssize_t; +# define PY_SSIZE_T_MAX INT_MAX +# define PY_SSIZE_T_MIN INT_MIN +typedef inquiry lenfunc; +typedef intargfunc ssizeargfunc; +typedef intintargfunc ssizessizeargfunc; +typedef intobjargproc ssizeobjargproc; +typedef intintobjargproc ssizessizeobjargproc; +typedef getreadbufferproc readbufferproc; +typedef getwritebufferproc writebufferproc; +typedef getsegcountproc segcountproc; +typedef getcharbufferproc charbufferproc; +static long PyNumber_AsSsize_t (PyObject *x, void *SWIGUNUSEDPARM(exc)) +{ + long result = 0; + PyObject *i = PyNumber_Int(x); + if (i) { + result = PyInt_AsLong(i); + Py_DECREF(i); + } + return result; +} +#endif + +#if PY_VERSION_HEX < 0x02050000 +#define PyInt_FromSize_t(x) PyInt_FromLong((long)x) +#endif + +#if PY_VERSION_HEX < 0x02040000 +#define Py_VISIT(op) \ + do { \ + if (op) { \ + int vret = visit((op), arg); \ + if (vret) \ + return vret; \ + } \ + } while (0) +#endif + +#if PY_VERSION_HEX < 0x02030000 +typedef struct { + PyTypeObject type; + PyNumberMethods as_number; + PyMappingMethods as_mapping; + PySequenceMethods as_sequence; + PyBufferProcs as_buffer; + PyObject *name, *slots; +} PyHeapTypeObject; +#endif + +#if PY_VERSION_HEX < 0x02030000 +typedef destructor freefunc; +#endif + +#if ((PY_MAJOR_VERSION == 2 && PY_MINOR_VERSION > 6) || \ + (PY_MAJOR_VERSION == 3 && PY_MINOR_VERSION > 0) || \ + (PY_MAJOR_VERSION > 3)) +# define SWIGPY_USE_CAPSULE +# define SWIGPY_CAPSULE_NAME ((char*)"swig_runtime_data" SWIG_RUNTIME_VERSION ".type_pointer_capsule" SWIG_TYPE_TABLE_NAME) +#endif + +#if PY_VERSION_HEX < 0x03020000 +#define PyDescr_TYPE(x) (((PyDescrObject *)(x))->d_type) +#define PyDescr_NAME(x) (((PyDescrObject *)(x))->d_name) +#endif + +/* ----------------------------------------------------------------------------- + * error manipulation + * ----------------------------------------------------------------------------- */ + +SWIGRUNTIME PyObject* +SWIG_Python_ErrorType(int code) { + PyObject* type = 0; + switch(code) { + case SWIG_MemoryError: + type = PyExc_MemoryError; + break; + case SWIG_IOError: + type = PyExc_IOError; + break; + case SWIG_RuntimeError: + type = PyExc_RuntimeError; + break; + case SWIG_IndexError: + type = PyExc_IndexError; + break; + case SWIG_TypeError: + type = PyExc_TypeError; + break; + case SWIG_DivisionByZero: + type = PyExc_ZeroDivisionError; + break; + case SWIG_OverflowError: + type = PyExc_OverflowError; + break; + case SWIG_SyntaxError: + type = PyExc_SyntaxError; + break; + case SWIG_ValueError: + type = PyExc_ValueError; + break; + case SWIG_SystemError: + type = PyExc_SystemError; + break; + case SWIG_AttributeError: + type = PyExc_AttributeError; + break; + default: + type = PyExc_RuntimeError; + } + return type; +} + + +SWIGRUNTIME void +SWIG_Python_AddErrorMsg(const char* mesg) +{ + PyObject *type = 0; + PyObject *value = 0; + PyObject *traceback = 0; + + if (PyErr_Occurred()) PyErr_Fetch(&type, &value, &traceback); + if (value) { + char *tmp; + PyObject *old_str = PyObject_Str(value); + PyErr_Clear(); + Py_XINCREF(type); + + PyErr_Format(type, "%s %s", tmp = SWIG_Python_str_AsChar(old_str), mesg); + SWIG_Python_str_DelForPy3(tmp); + Py_DECREF(old_str); + Py_DECREF(value); + } else { + PyErr_SetString(PyExc_RuntimeError, mesg); + } +} + +#if defined(SWIG_PYTHON_NO_THREADS) +# if defined(SWIG_PYTHON_THREADS) +# undef SWIG_PYTHON_THREADS +# endif +#endif +#if defined(SWIG_PYTHON_THREADS) /* Threading support is enabled */ +# if !defined(SWIG_PYTHON_USE_GIL) && !defined(SWIG_PYTHON_NO_USE_GIL) +# if (PY_VERSION_HEX >= 0x02030000) /* For 2.3 or later, use the PyGILState calls */ +# define SWIG_PYTHON_USE_GIL +# endif +# endif +# if defined(SWIG_PYTHON_USE_GIL) /* Use PyGILState threads calls */ +# ifndef SWIG_PYTHON_INITIALIZE_THREADS +# define SWIG_PYTHON_INITIALIZE_THREADS PyEval_InitThreads() +# endif +# ifdef __cplusplus /* C++ code */ + class SWIG_Python_Thread_Block { + bool status; + PyGILState_STATE state; + public: + void end() { if (status) { PyGILState_Release(state); status = false;} } + SWIG_Python_Thread_Block() : status(true), state(PyGILState_Ensure()) {} + ~SWIG_Python_Thread_Block() { end(); } + }; + class SWIG_Python_Thread_Allow { + bool status; + PyThreadState *save; + public: + void end() { if (status) { PyEval_RestoreThread(save); status = false; }} + SWIG_Python_Thread_Allow() : status(true), save(PyEval_SaveThread()) {} + ~SWIG_Python_Thread_Allow() { end(); } + }; +# define SWIG_PYTHON_THREAD_BEGIN_BLOCK SWIG_Python_Thread_Block _swig_thread_block +# define SWIG_PYTHON_THREAD_END_BLOCK _swig_thread_block.end() +# define SWIG_PYTHON_THREAD_BEGIN_ALLOW SWIG_Python_Thread_Allow _swig_thread_allow +# define SWIG_PYTHON_THREAD_END_ALLOW _swig_thread_allow.end() +# else /* C code */ +# define SWIG_PYTHON_THREAD_BEGIN_BLOCK PyGILState_STATE _swig_thread_block = PyGILState_Ensure() +# define SWIG_PYTHON_THREAD_END_BLOCK PyGILState_Release(_swig_thread_block) +# define SWIG_PYTHON_THREAD_BEGIN_ALLOW PyThreadState *_swig_thread_allow = PyEval_SaveThread() +# define SWIG_PYTHON_THREAD_END_ALLOW PyEval_RestoreThread(_swig_thread_allow) +# endif +# else /* Old thread way, not implemented, user must provide it */ +# if !defined(SWIG_PYTHON_INITIALIZE_THREADS) +# define SWIG_PYTHON_INITIALIZE_THREADS +# endif +# if !defined(SWIG_PYTHON_THREAD_BEGIN_BLOCK) +# define SWIG_PYTHON_THREAD_BEGIN_BLOCK +# endif +# if !defined(SWIG_PYTHON_THREAD_END_BLOCK) +# define SWIG_PYTHON_THREAD_END_BLOCK +# endif +# if !defined(SWIG_PYTHON_THREAD_BEGIN_ALLOW) +# define SWIG_PYTHON_THREAD_BEGIN_ALLOW +# endif +# if !defined(SWIG_PYTHON_THREAD_END_ALLOW) +# define SWIG_PYTHON_THREAD_END_ALLOW +# endif +# endif +#else /* No thread support */ +# define SWIG_PYTHON_INITIALIZE_THREADS +# define SWIG_PYTHON_THREAD_BEGIN_BLOCK +# define SWIG_PYTHON_THREAD_END_BLOCK +# define SWIG_PYTHON_THREAD_BEGIN_ALLOW +# define SWIG_PYTHON_THREAD_END_ALLOW +#endif + +/* ----------------------------------------------------------------------------- + * Python API portion that goes into the runtime + * ----------------------------------------------------------------------------- */ + +#ifdef __cplusplus +extern "C" { +#endif + +/* ----------------------------------------------------------------------------- + * Constant declarations + * ----------------------------------------------------------------------------- */ + +/* Constant Types */ +#define SWIG_PY_POINTER 4 +#define SWIG_PY_BINARY 5 + +/* Constant information structure */ +typedef struct swig_const_info { + int type; + char *name; + long lvalue; + double dvalue; + void *pvalue; + swig_type_info **ptype; +} swig_const_info; + + +/* ----------------------------------------------------------------------------- + * Wrapper of PyInstanceMethod_New() used in Python 3 + * It is exported to the generated module, used for -fastproxy + * ----------------------------------------------------------------------------- */ +#if PY_VERSION_HEX >= 0x03000000 +SWIGRUNTIME PyObject* SWIG_PyInstanceMethod_New(PyObject *SWIGUNUSEDPARM(self), PyObject *func) +{ + return PyInstanceMethod_New(func); +} +#else +SWIGRUNTIME PyObject* SWIG_PyInstanceMethod_New(PyObject *SWIGUNUSEDPARM(self), PyObject *SWIGUNUSEDPARM(func)) +{ + return NULL; +} +#endif + +#ifdef __cplusplus +} +#endif + + +/* ----------------------------------------------------------------------------- + * pyrun.swg + * + * This file contains the runtime support for Python modules + * and includes code for managing global variables and pointer + * type checking. + * + * ----------------------------------------------------------------------------- */ + +/* Common SWIG API */ + +/* for raw pointers */ +#define SWIG_Python_ConvertPtr(obj, pptr, type, flags) SWIG_Python_ConvertPtrAndOwn(obj, pptr, type, flags, 0) +#define SWIG_ConvertPtr(obj, pptr, type, flags) SWIG_Python_ConvertPtr(obj, pptr, type, flags) +#define SWIG_ConvertPtrAndOwn(obj,pptr,type,flags,own) SWIG_Python_ConvertPtrAndOwn(obj, pptr, type, flags, own) + +#ifdef SWIGPYTHON_BUILTIN +#define SWIG_NewPointerObj(ptr, type, flags) SWIG_Python_NewPointerObj(self, ptr, type, flags) +#else +#define SWIG_NewPointerObj(ptr, type, flags) SWIG_Python_NewPointerObj(NULL, ptr, type, flags) +#endif + +#define SWIG_InternalNewPointerObj(ptr, type, flags) SWIG_Python_NewPointerObj(NULL, ptr, type, flags) + +#define SWIG_CheckImplicit(ty) SWIG_Python_CheckImplicit(ty) +#define SWIG_AcquirePtr(ptr, src) SWIG_Python_AcquirePtr(ptr, src) +#define swig_owntype int + +/* for raw packed data */ +#define SWIG_ConvertPacked(obj, ptr, sz, ty) SWIG_Python_ConvertPacked(obj, ptr, sz, ty) +#define SWIG_NewPackedObj(ptr, sz, type) SWIG_Python_NewPackedObj(ptr, sz, type) + +/* for class or struct pointers */ +#define SWIG_ConvertInstance(obj, pptr, type, flags) SWIG_ConvertPtr(obj, pptr, type, flags) +#define SWIG_NewInstanceObj(ptr, type, flags) SWIG_NewPointerObj(ptr, type, flags) + +/* for C or C++ function pointers */ +#define SWIG_ConvertFunctionPtr(obj, pptr, type) SWIG_Python_ConvertFunctionPtr(obj, pptr, type) +#define SWIG_NewFunctionPtrObj(ptr, type) SWIG_Python_NewPointerObj(NULL, ptr, type, 0) + +/* for C++ member pointers, ie, member methods */ +#define SWIG_ConvertMember(obj, ptr, sz, ty) SWIG_Python_ConvertPacked(obj, ptr, sz, ty) +#define SWIG_NewMemberObj(ptr, sz, type) SWIG_Python_NewPackedObj(ptr, sz, type) + + +/* Runtime API */ + +#define SWIG_GetModule(clientdata) SWIG_Python_GetModule(clientdata) +#define SWIG_SetModule(clientdata, pointer) SWIG_Python_SetModule(pointer) +#define SWIG_NewClientData(obj) SwigPyClientData_New(obj) + +#define SWIG_SetErrorObj SWIG_Python_SetErrorObj +#define SWIG_SetErrorMsg SWIG_Python_SetErrorMsg +#define SWIG_ErrorType(code) SWIG_Python_ErrorType(code) +#define SWIG_Error(code, msg) SWIG_Python_SetErrorMsg(SWIG_ErrorType(code), msg) +#define SWIG_fail goto fail + + +/* Runtime API implementation */ + +/* Error manipulation */ + +SWIGINTERN void +SWIG_Python_SetErrorObj(PyObject *errtype, PyObject *obj) { + SWIG_PYTHON_THREAD_BEGIN_BLOCK; + PyErr_SetObject(errtype, obj); + Py_DECREF(obj); + SWIG_PYTHON_THREAD_END_BLOCK; +} + +SWIGINTERN void +SWIG_Python_SetErrorMsg(PyObject *errtype, const char *msg) { + SWIG_PYTHON_THREAD_BEGIN_BLOCK; + PyErr_SetString(errtype, msg); + SWIG_PYTHON_THREAD_END_BLOCK; +} + +#define SWIG_Python_Raise(obj, type, desc) SWIG_Python_SetErrorObj(SWIG_Python_ExceptionType(desc), obj) + +/* Set a constant value */ + +#if defined(SWIGPYTHON_BUILTIN) + +SWIGINTERN void +SwigPyBuiltin_AddPublicSymbol(PyObject *seq, const char *key) { + PyObject *s = PyString_InternFromString(key); + PyList_Append(seq, s); + Py_DECREF(s); +} + +SWIGINTERN void +SWIG_Python_SetConstant(PyObject *d, PyObject *public_interface, const char *name, PyObject *obj) { +#if PY_VERSION_HEX < 0x02030000 + PyDict_SetItemString(d, (char *)name, obj); +#else + PyDict_SetItemString(d, name, obj); +#endif + Py_DECREF(obj); + if (public_interface) + SwigPyBuiltin_AddPublicSymbol(public_interface, name); +} + +#else + +SWIGINTERN void +SWIG_Python_SetConstant(PyObject *d, const char *name, PyObject *obj) { +#if PY_VERSION_HEX < 0x02030000 + PyDict_SetItemString(d, (char *)name, obj); +#else + PyDict_SetItemString(d, name, obj); +#endif + Py_DECREF(obj); +} + +#endif + +/* Append a value to the result obj */ + +SWIGINTERN PyObject* +SWIG_Python_AppendOutput(PyObject* result, PyObject* obj) { +#if !defined(SWIG_PYTHON_OUTPUT_TUPLE) + if (!result) { + result = obj; + } else if (result == Py_None) { + Py_DECREF(result); + result = obj; + } else { + if (!PyList_Check(result)) { + PyObject *o2 = result; + result = PyList_New(1); + PyList_SetItem(result, 0, o2); + } + PyList_Append(result,obj); + Py_DECREF(obj); + } + return result; +#else + PyObject* o2; + PyObject* o3; + if (!result) { + result = obj; + } else if (result == Py_None) { + Py_DECREF(result); + result = obj; + } else { + if (!PyTuple_Check(result)) { + o2 = result; + result = PyTuple_New(1); + PyTuple_SET_ITEM(result, 0, o2); + } + o3 = PyTuple_New(1); + PyTuple_SET_ITEM(o3, 0, obj); + o2 = result; + result = PySequence_Concat(o2, o3); + Py_DECREF(o2); + Py_DECREF(o3); + } + return result; +#endif +} + +/* Unpack the argument tuple */ + +SWIGINTERN int +SWIG_Python_UnpackTuple(PyObject *args, const char *name, Py_ssize_t min, Py_ssize_t max, PyObject **objs) +{ + if (!args) { + if (!min && !max) { + return 1; + } else { + PyErr_Format(PyExc_TypeError, "%s expected %s%d arguments, got none", + name, (min == max ? "" : "at least "), (int)min); + return 0; + } + } + if (!PyTuple_Check(args)) { + if (min <= 1 && max >= 1) { + int i; + objs[0] = args; + for (i = 1; i < max; ++i) { + objs[i] = 0; + } + return 2; + } + PyErr_SetString(PyExc_SystemError, "UnpackTuple() argument list is not a tuple"); + return 0; + } else { + Py_ssize_t l = PyTuple_GET_SIZE(args); + if (l < min) { + PyErr_Format(PyExc_TypeError, "%s expected %s%d arguments, got %d", + name, (min == max ? "" : "at least "), (int)min, (int)l); + return 0; + } else if (l > max) { + PyErr_Format(PyExc_TypeError, "%s expected %s%d arguments, got %d", + name, (min == max ? "" : "at most "), (int)max, (int)l); + return 0; + } else { + int i; + for (i = 0; i < l; ++i) { + objs[i] = PyTuple_GET_ITEM(args, i); + } + for (; l < max; ++l) { + objs[l] = 0; + } + return i + 1; + } + } +} + +/* A functor is a function object with one single object argument */ +#if PY_VERSION_HEX >= 0x02020000 +#define SWIG_Python_CallFunctor(functor, obj) PyObject_CallFunctionObjArgs(functor, obj, NULL); +#else +#define SWIG_Python_CallFunctor(functor, obj) PyObject_CallFunction(functor, "O", obj); +#endif + +/* + Helper for static pointer initialization for both C and C++ code, for example + static PyObject *SWIG_STATIC_POINTER(MyVar) = NewSomething(...); +*/ +#ifdef __cplusplus +#define SWIG_STATIC_POINTER(var) var +#else +#define SWIG_STATIC_POINTER(var) var = 0; if (!var) var +#endif + +/* ----------------------------------------------------------------------------- + * Pointer declarations + * ----------------------------------------------------------------------------- */ + +/* Flags for new pointer objects */ +#define SWIG_POINTER_NOSHADOW (SWIG_POINTER_OWN << 1) +#define SWIG_POINTER_NEW (SWIG_POINTER_NOSHADOW | SWIG_POINTER_OWN) + +#define SWIG_POINTER_IMPLICIT_CONV (SWIG_POINTER_DISOWN << 1) + +#define SWIG_BUILTIN_TP_INIT (SWIG_POINTER_OWN << 2) +#define SWIG_BUILTIN_INIT (SWIG_BUILTIN_TP_INIT | SWIG_POINTER_OWN) + +#ifdef __cplusplus +extern "C" { +#endif + +/* How to access Py_None */ +#if defined(_WIN32) || defined(__WIN32__) || defined(__CYGWIN__) +# ifndef SWIG_PYTHON_NO_BUILD_NONE +# ifndef SWIG_PYTHON_BUILD_NONE +# define SWIG_PYTHON_BUILD_NONE +# endif +# endif +#endif + +#ifdef SWIG_PYTHON_BUILD_NONE +# ifdef Py_None +# undef Py_None +# define Py_None SWIG_Py_None() +# endif +SWIGRUNTIMEINLINE PyObject * +_SWIG_Py_None(void) +{ + PyObject *none = Py_BuildValue((char*)""); + Py_DECREF(none); + return none; +} +SWIGRUNTIME PyObject * +SWIG_Py_None(void) +{ + static PyObject *SWIG_STATIC_POINTER(none) = _SWIG_Py_None(); + return none; +} +#endif + +/* The python void return value */ + +SWIGRUNTIMEINLINE PyObject * +SWIG_Py_Void(void) +{ + PyObject *none = Py_None; + Py_INCREF(none); + return none; +} + +/* SwigPyClientData */ + +typedef struct { + PyObject *klass; + PyObject *newraw; + PyObject *newargs; + PyObject *destroy; + int delargs; + int implicitconv; + PyTypeObject *pytype; +} SwigPyClientData; + +SWIGRUNTIMEINLINE int +SWIG_Python_CheckImplicit(swig_type_info *ty) +{ + SwigPyClientData *data = (SwigPyClientData *)ty->clientdata; + return data ? data->implicitconv : 0; +} + +SWIGRUNTIMEINLINE PyObject * +SWIG_Python_ExceptionType(swig_type_info *desc) { + SwigPyClientData *data = desc ? (SwigPyClientData *) desc->clientdata : 0; + PyObject *klass = data ? data->klass : 0; + return (klass ? klass : PyExc_RuntimeError); +} + + +SWIGRUNTIME SwigPyClientData * +SwigPyClientData_New(PyObject* obj) +{ + if (!obj) { + return 0; + } else { + SwigPyClientData *data = (SwigPyClientData *)malloc(sizeof(SwigPyClientData)); + /* the klass element */ + data->klass = obj; + Py_INCREF(data->klass); + /* the newraw method and newargs arguments used to create a new raw instance */ + if (PyClass_Check(obj)) { + data->newraw = 0; + data->newargs = obj; + Py_INCREF(obj); + } else { +#if (PY_VERSION_HEX < 0x02020000) + data->newraw = 0; +#else + data->newraw = PyObject_GetAttrString(data->klass, (char *)"__new__"); +#endif + if (data->newraw) { + Py_INCREF(data->newraw); + data->newargs = PyTuple_New(1); + PyTuple_SetItem(data->newargs, 0, obj); + } else { + data->newargs = obj; + } + Py_INCREF(data->newargs); + } + /* the destroy method, aka as the C++ delete method */ + data->destroy = PyObject_GetAttrString(data->klass, (char *)"__swig_destroy__"); + if (PyErr_Occurred()) { + PyErr_Clear(); + data->destroy = 0; + } + if (data->destroy) { + int flags; + Py_INCREF(data->destroy); + flags = PyCFunction_GET_FLAGS(data->destroy); +#ifdef METH_O + data->delargs = !(flags & (METH_O)); +#else + data->delargs = 0; +#endif + } else { + data->delargs = 0; + } + data->implicitconv = 0; + data->pytype = 0; + return data; + } +} + +SWIGRUNTIME void +SwigPyClientData_Del(SwigPyClientData *data) { + Py_XDECREF(data->newraw); + Py_XDECREF(data->newargs); + Py_XDECREF(data->destroy); +} + +/* =============== SwigPyObject =====================*/ + +typedef struct { + PyObject_HEAD + void *ptr; + swig_type_info *ty; + int own; + PyObject *next; +#ifdef SWIGPYTHON_BUILTIN + PyObject *dict; +#endif +} SwigPyObject; + +SWIGRUNTIME PyObject * +SwigPyObject_long(SwigPyObject *v) +{ + return PyLong_FromVoidPtr(v->ptr); +} + +SWIGRUNTIME PyObject * +SwigPyObject_format(const char* fmt, SwigPyObject *v) +{ + PyObject *res = NULL; + PyObject *args = PyTuple_New(1); + if (args) { + if (PyTuple_SetItem(args, 0, SwigPyObject_long(v)) == 0) { + PyObject *ofmt = SWIG_Python_str_FromChar(fmt); + if (ofmt) { +#if PY_VERSION_HEX >= 0x03000000 + res = PyUnicode_Format(ofmt,args); +#else + res = PyString_Format(ofmt,args); +#endif + Py_DECREF(ofmt); + } + Py_DECREF(args); + } + } + return res; +} + +SWIGRUNTIME PyObject * +SwigPyObject_oct(SwigPyObject *v) +{ + return SwigPyObject_format("%o",v); +} + +SWIGRUNTIME PyObject * +SwigPyObject_hex(SwigPyObject *v) +{ + return SwigPyObject_format("%x",v); +} + +SWIGRUNTIME PyObject * +#ifdef METH_NOARGS +SwigPyObject_repr(SwigPyObject *v) +#else +SwigPyObject_repr(SwigPyObject *v, PyObject *args) +#endif +{ + const char *name = SWIG_TypePrettyName(v->ty); + PyObject *repr = SWIG_Python_str_FromFormat("", (name ? name : "unknown"), (void *)v); + if (v->next) { +# ifdef METH_NOARGS + PyObject *nrep = SwigPyObject_repr((SwigPyObject *)v->next); +# else + PyObject *nrep = SwigPyObject_repr((SwigPyObject *)v->next, args); +# endif +# if PY_VERSION_HEX >= 0x03000000 + PyObject *joined = PyUnicode_Concat(repr, nrep); + Py_DecRef(repr); + Py_DecRef(nrep); + repr = joined; +# else + PyString_ConcatAndDel(&repr,nrep); +# endif + } + return repr; +} + +SWIGRUNTIME int +SwigPyObject_compare(SwigPyObject *v, SwigPyObject *w) +{ + void *i = v->ptr; + void *j = w->ptr; + return (i < j) ? -1 : ((i > j) ? 1 : 0); +} + +/* Added for Python 3.x, would it also be useful for Python 2.x? */ +SWIGRUNTIME PyObject* +SwigPyObject_richcompare(SwigPyObject *v, SwigPyObject *w, int op) +{ + PyObject* res; + if( op != Py_EQ && op != Py_NE ) { + Py_INCREF(Py_NotImplemented); + return Py_NotImplemented; + } + res = PyBool_FromLong( (SwigPyObject_compare(v, w)==0) == (op == Py_EQ) ? 1 : 0); + return res; +} + + +SWIGRUNTIME PyTypeObject* SwigPyObject_TypeOnce(void); + +#ifdef SWIGPYTHON_BUILTIN +static swig_type_info *SwigPyObject_stype = 0; +SWIGRUNTIME PyTypeObject* +SwigPyObject_type(void) { + SwigPyClientData *cd; + assert(SwigPyObject_stype); + cd = (SwigPyClientData*) SwigPyObject_stype->clientdata; + assert(cd); + assert(cd->pytype); + return cd->pytype; +} +#else +SWIGRUNTIME PyTypeObject* +SwigPyObject_type(void) { + static PyTypeObject *SWIG_STATIC_POINTER(type) = SwigPyObject_TypeOnce(); + return type; +} +#endif + +SWIGRUNTIMEINLINE int +SwigPyObject_Check(PyObject *op) { +#ifdef SWIGPYTHON_BUILTIN + PyTypeObject *target_tp = SwigPyObject_type(); + if (PyType_IsSubtype(op->ob_type, target_tp)) + return 1; + return (strcmp(op->ob_type->tp_name, "SwigPyObject") == 0); +#else + return (Py_TYPE(op) == SwigPyObject_type()) + || (strcmp(Py_TYPE(op)->tp_name,"SwigPyObject") == 0); +#endif +} + +SWIGRUNTIME PyObject * +SwigPyObject_New(void *ptr, swig_type_info *ty, int own); + +SWIGRUNTIME void +SwigPyObject_dealloc(PyObject *v) +{ + SwigPyObject *sobj = (SwigPyObject *) v; + PyObject *next = sobj->next; + if (sobj->own == SWIG_POINTER_OWN) { + swig_type_info *ty = sobj->ty; + SwigPyClientData *data = ty ? (SwigPyClientData *) ty->clientdata : 0; + PyObject *destroy = data ? data->destroy : 0; + if (destroy) { + /* destroy is always a VARARGS method */ + PyObject *res; + if (data->delargs) { + /* we need to create a temporary object to carry the destroy operation */ + PyObject *tmp = SwigPyObject_New(sobj->ptr, ty, 0); + res = SWIG_Python_CallFunctor(destroy, tmp); + Py_DECREF(tmp); + } else { + PyCFunction meth = PyCFunction_GET_FUNCTION(destroy); + PyObject *mself = PyCFunction_GET_SELF(destroy); + res = ((*meth)(mself, v)); + } + Py_XDECREF(res); + } +#if !defined(SWIG_PYTHON_SILENT_MEMLEAK) + else { + const char *name = SWIG_TypePrettyName(ty); + printf("swig/python detected a memory leak of type '%s', no destructor found.\n", (name ? name : "unknown")); + } +#endif + } + Py_XDECREF(next); + PyObject_DEL(v); +} + +SWIGRUNTIME PyObject* +SwigPyObject_append(PyObject* v, PyObject* next) +{ + SwigPyObject *sobj = (SwigPyObject *) v; +#ifndef METH_O + PyObject *tmp = 0; + if (!PyArg_ParseTuple(next,(char *)"O:append", &tmp)) return NULL; + next = tmp; +#endif + if (!SwigPyObject_Check(next)) { + return NULL; + } + sobj->next = next; + Py_INCREF(next); + return SWIG_Py_Void(); +} + +SWIGRUNTIME PyObject* +#ifdef METH_NOARGS +SwigPyObject_next(PyObject* v) +#else +SwigPyObject_next(PyObject* v, PyObject *SWIGUNUSEDPARM(args)) +#endif +{ + SwigPyObject *sobj = (SwigPyObject *) v; + if (sobj->next) { + Py_INCREF(sobj->next); + return sobj->next; + } else { + return SWIG_Py_Void(); + } +} + +SWIGINTERN PyObject* +#ifdef METH_NOARGS +SwigPyObject_disown(PyObject *v) +#else +SwigPyObject_disown(PyObject* v, PyObject *SWIGUNUSEDPARM(args)) +#endif +{ + SwigPyObject *sobj = (SwigPyObject *)v; + sobj->own = 0; + return SWIG_Py_Void(); +} + +SWIGINTERN PyObject* +#ifdef METH_NOARGS +SwigPyObject_acquire(PyObject *v) +#else +SwigPyObject_acquire(PyObject* v, PyObject *SWIGUNUSEDPARM(args)) +#endif +{ + SwigPyObject *sobj = (SwigPyObject *)v; + sobj->own = SWIG_POINTER_OWN; + return SWIG_Py_Void(); +} + +SWIGINTERN PyObject* +SwigPyObject_own(PyObject *v, PyObject *args) +{ + PyObject *val = 0; +#if (PY_VERSION_HEX < 0x02020000) + if (!PyArg_ParseTuple(args,(char *)"|O:own",&val)) +#elif (PY_VERSION_HEX < 0x02050000) + if (!PyArg_UnpackTuple(args, (char *)"own", 0, 1, &val)) +#else + if (!PyArg_UnpackTuple(args, "own", 0, 1, &val)) +#endif + { + return NULL; + } + else + { + SwigPyObject *sobj = (SwigPyObject *)v; + PyObject *obj = PyBool_FromLong(sobj->own); + if (val) { +#ifdef METH_NOARGS + if (PyObject_IsTrue(val)) { + SwigPyObject_acquire(v); + } else { + SwigPyObject_disown(v); + } +#else + if (PyObject_IsTrue(val)) { + SwigPyObject_acquire(v,args); + } else { + SwigPyObject_disown(v,args); + } +#endif + } + return obj; + } +} + +#ifdef METH_O +static PyMethodDef +swigobject_methods[] = { + {(char *)"disown", (PyCFunction)SwigPyObject_disown, METH_NOARGS, (char *)"releases ownership of the pointer"}, + {(char *)"acquire", (PyCFunction)SwigPyObject_acquire, METH_NOARGS, (char *)"acquires ownership of the pointer"}, + {(char *)"own", (PyCFunction)SwigPyObject_own, METH_VARARGS, (char *)"returns/sets ownership of the pointer"}, + {(char *)"append", (PyCFunction)SwigPyObject_append, METH_O, (char *)"appends another 'this' object"}, + {(char *)"next", (PyCFunction)SwigPyObject_next, METH_NOARGS, (char *)"returns the next 'this' object"}, + {(char *)"__repr__",(PyCFunction)SwigPyObject_repr, METH_NOARGS, (char *)"returns object representation"}, + {0, 0, 0, 0} +}; +#else +static PyMethodDef +swigobject_methods[] = { + {(char *)"disown", (PyCFunction)SwigPyObject_disown, METH_VARARGS, (char *)"releases ownership of the pointer"}, + {(char *)"acquire", (PyCFunction)SwigPyObject_acquire, METH_VARARGS, (char *)"aquires ownership of the pointer"}, + {(char *)"own", (PyCFunction)SwigPyObject_own, METH_VARARGS, (char *)"returns/sets ownership of the pointer"}, + {(char *)"append", (PyCFunction)SwigPyObject_append, METH_VARARGS, (char *)"appends another 'this' object"}, + {(char *)"next", (PyCFunction)SwigPyObject_next, METH_VARARGS, (char *)"returns the next 'this' object"}, + {(char *)"__repr__",(PyCFunction)SwigPyObject_repr, METH_VARARGS, (char *)"returns object representation"}, + {0, 0, 0, 0} +}; +#endif + +#if PY_VERSION_HEX < 0x02020000 +SWIGINTERN PyObject * +SwigPyObject_getattr(SwigPyObject *sobj,char *name) +{ + return Py_FindMethod(swigobject_methods, (PyObject *)sobj, name); +} +#endif + +SWIGRUNTIME PyTypeObject* +SwigPyObject_TypeOnce(void) { + static char swigobject_doc[] = "Swig object carries a C/C++ instance pointer"; + + static PyNumberMethods SwigPyObject_as_number = { + (binaryfunc)0, /*nb_add*/ + (binaryfunc)0, /*nb_subtract*/ + (binaryfunc)0, /*nb_multiply*/ + /* nb_divide removed in Python 3 */ +#if PY_VERSION_HEX < 0x03000000 + (binaryfunc)0, /*nb_divide*/ +#endif + (binaryfunc)0, /*nb_remainder*/ + (binaryfunc)0, /*nb_divmod*/ + (ternaryfunc)0,/*nb_power*/ + (unaryfunc)0, /*nb_negative*/ + (unaryfunc)0, /*nb_positive*/ + (unaryfunc)0, /*nb_absolute*/ + (inquiry)0, /*nb_nonzero*/ + 0, /*nb_invert*/ + 0, /*nb_lshift*/ + 0, /*nb_rshift*/ + 0, /*nb_and*/ + 0, /*nb_xor*/ + 0, /*nb_or*/ +#if PY_VERSION_HEX < 0x03000000 + 0, /*nb_coerce*/ +#endif + (unaryfunc)SwigPyObject_long, /*nb_int*/ +#if PY_VERSION_HEX < 0x03000000 + (unaryfunc)SwigPyObject_long, /*nb_long*/ +#else + 0, /*nb_reserved*/ +#endif + (unaryfunc)0, /*nb_float*/ +#if PY_VERSION_HEX < 0x03000000 + (unaryfunc)SwigPyObject_oct, /*nb_oct*/ + (unaryfunc)SwigPyObject_hex, /*nb_hex*/ +#endif +#if PY_VERSION_HEX >= 0x03000000 /* 3.0 */ + 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0 /* nb_inplace_add -> nb_index, nb_inplace_divide removed */ +#elif PY_VERSION_HEX >= 0x02050000 /* 2.5.0 */ + 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0 /* nb_inplace_add -> nb_index */ +#elif PY_VERSION_HEX >= 0x02020000 /* 2.2.0 */ + 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0 /* nb_inplace_add -> nb_inplace_true_divide */ +#elif PY_VERSION_HEX >= 0x02000000 /* 2.0.0 */ + 0,0,0,0,0,0,0,0,0,0,0 /* nb_inplace_add -> nb_inplace_or */ +#endif + }; + + static PyTypeObject swigpyobject_type; + static int type_init = 0; + if (!type_init) { + const PyTypeObject tmp = { + /* PyObject header changed in Python 3 */ +#if PY_VERSION_HEX >= 0x03000000 + PyVarObject_HEAD_INIT(NULL, 0) +#else + PyObject_HEAD_INIT(NULL) + 0, /* ob_size */ +#endif + (char *)"SwigPyObject", /* tp_name */ + sizeof(SwigPyObject), /* tp_basicsize */ + 0, /* tp_itemsize */ + (destructor)SwigPyObject_dealloc, /* tp_dealloc */ + 0, /* tp_print */ +#if PY_VERSION_HEX < 0x02020000 + (getattrfunc)SwigPyObject_getattr, /* tp_getattr */ +#else + (getattrfunc)0, /* tp_getattr */ +#endif + (setattrfunc)0, /* tp_setattr */ +#if PY_VERSION_HEX >= 0x03000000 + 0, /* tp_reserved in 3.0.1, tp_compare in 3.0.0 but not used */ +#else + (cmpfunc)SwigPyObject_compare, /* tp_compare */ +#endif + (reprfunc)SwigPyObject_repr, /* tp_repr */ + &SwigPyObject_as_number, /* tp_as_number */ + 0, /* tp_as_sequence */ + 0, /* tp_as_mapping */ + (hashfunc)0, /* tp_hash */ + (ternaryfunc)0, /* tp_call */ + 0, /* tp_str */ + PyObject_GenericGetAttr, /* tp_getattro */ + 0, /* tp_setattro */ + 0, /* tp_as_buffer */ + Py_TPFLAGS_DEFAULT, /* tp_flags */ + swigobject_doc, /* tp_doc */ + 0, /* tp_traverse */ + 0, /* tp_clear */ + (richcmpfunc)SwigPyObject_richcompare,/* tp_richcompare */ + 0, /* tp_weaklistoffset */ +#if PY_VERSION_HEX >= 0x02020000 + 0, /* tp_iter */ + 0, /* tp_iternext */ + swigobject_methods, /* tp_methods */ + 0, /* 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_new */ + 0, /* tp_free */ + 0, /* tp_is_gc */ + 0, /* tp_bases */ + 0, /* tp_mro */ + 0, /* tp_cache */ + 0, /* tp_subclasses */ + 0, /* tp_weaklist */ +#endif +#if PY_VERSION_HEX >= 0x02030000 + 0, /* tp_del */ +#endif +#if PY_VERSION_HEX >= 0x02060000 + 0, /* tp_version */ +#endif +#ifdef COUNT_ALLOCS + 0,0,0,0 /* tp_alloc -> tp_next */ +#endif + }; + swigpyobject_type = tmp; + type_init = 1; +#if PY_VERSION_HEX < 0x02020000 + swigpyobject_type.ob_type = &PyType_Type; +#else + if (PyType_Ready(&swigpyobject_type) < 0) + return NULL; +#endif + } + return &swigpyobject_type; +} + +SWIGRUNTIME PyObject * +SwigPyObject_New(void *ptr, swig_type_info *ty, int own) +{ + SwigPyObject *sobj = PyObject_NEW(SwigPyObject, SwigPyObject_type()); + if (sobj) { + sobj->ptr = ptr; + sobj->ty = ty; + sobj->own = own; + sobj->next = 0; + } + return (PyObject *)sobj; +} + +/* ----------------------------------------------------------------------------- + * Implements a simple Swig Packed type, and use it instead of string + * ----------------------------------------------------------------------------- */ + +typedef struct { + PyObject_HEAD + void *pack; + swig_type_info *ty; + size_t size; +} SwigPyPacked; + +SWIGRUNTIME int +SwigPyPacked_print(SwigPyPacked *v, FILE *fp, int SWIGUNUSEDPARM(flags)) +{ + char result[SWIG_BUFFER_SIZE]; + fputs("pack, v->size, 0, sizeof(result))) { + fputs("at ", fp); + fputs(result, fp); + } + fputs(v->ty->name,fp); + fputs(">", fp); + return 0; +} + +SWIGRUNTIME PyObject * +SwigPyPacked_repr(SwigPyPacked *v) +{ + char result[SWIG_BUFFER_SIZE]; + if (SWIG_PackDataName(result, v->pack, v->size, 0, sizeof(result))) { + return SWIG_Python_str_FromFormat("", result, v->ty->name); + } else { + return SWIG_Python_str_FromFormat("", v->ty->name); + } +} + +SWIGRUNTIME PyObject * +SwigPyPacked_str(SwigPyPacked *v) +{ + char result[SWIG_BUFFER_SIZE]; + if (SWIG_PackDataName(result, v->pack, v->size, 0, sizeof(result))){ + return SWIG_Python_str_FromFormat("%s%s", result, v->ty->name); + } else { + return SWIG_Python_str_FromChar(v->ty->name); + } +} + +SWIGRUNTIME int +SwigPyPacked_compare(SwigPyPacked *v, SwigPyPacked *w) +{ + size_t i = v->size; + size_t j = w->size; + int s = (i < j) ? -1 : ((i > j) ? 1 : 0); + return s ? s : strncmp((char *)v->pack, (char *)w->pack, 2*v->size); +} + +SWIGRUNTIME PyTypeObject* SwigPyPacked_TypeOnce(void); + +SWIGRUNTIME PyTypeObject* +SwigPyPacked_type(void) { + static PyTypeObject *SWIG_STATIC_POINTER(type) = SwigPyPacked_TypeOnce(); + return type; +} + +SWIGRUNTIMEINLINE int +SwigPyPacked_Check(PyObject *op) { + return ((op)->ob_type == SwigPyPacked_TypeOnce()) + || (strcmp((op)->ob_type->tp_name,"SwigPyPacked") == 0); +} + +SWIGRUNTIME void +SwigPyPacked_dealloc(PyObject *v) +{ + if (SwigPyPacked_Check(v)) { + SwigPyPacked *sobj = (SwigPyPacked *) v; + free(sobj->pack); + } + PyObject_DEL(v); +} + +SWIGRUNTIME PyTypeObject* +SwigPyPacked_TypeOnce(void) { + static char swigpacked_doc[] = "Swig object carries a C/C++ instance pointer"; + static PyTypeObject swigpypacked_type; + static int type_init = 0; + if (!type_init) { + const PyTypeObject tmp = { + /* PyObject header changed in Python 3 */ +#if PY_VERSION_HEX>=0x03000000 + PyVarObject_HEAD_INIT(NULL, 0) +#else + PyObject_HEAD_INIT(NULL) + 0, /* ob_size */ +#endif + (char *)"SwigPyPacked", /* tp_name */ + sizeof(SwigPyPacked), /* tp_basicsize */ + 0, /* tp_itemsize */ + (destructor)SwigPyPacked_dealloc, /* tp_dealloc */ + (printfunc)SwigPyPacked_print, /* tp_print */ + (getattrfunc)0, /* tp_getattr */ + (setattrfunc)0, /* tp_setattr */ +#if PY_VERSION_HEX>=0x03000000 + 0, /* tp_reserved in 3.0.1 */ +#else + (cmpfunc)SwigPyPacked_compare, /* tp_compare */ +#endif + (reprfunc)SwigPyPacked_repr, /* tp_repr */ + 0, /* tp_as_number */ + 0, /* tp_as_sequence */ + 0, /* tp_as_mapping */ + (hashfunc)0, /* tp_hash */ + (ternaryfunc)0, /* tp_call */ + (reprfunc)SwigPyPacked_str, /* tp_str */ + PyObject_GenericGetAttr, /* tp_getattro */ + 0, /* tp_setattro */ + 0, /* tp_as_buffer */ + Py_TPFLAGS_DEFAULT, /* tp_flags */ + swigpacked_doc, /* tp_doc */ + 0, /* tp_traverse */ + 0, /* tp_clear */ + 0, /* tp_richcompare */ + 0, /* tp_weaklistoffset */ +#if PY_VERSION_HEX >= 0x02020000 + 0, /* tp_iter */ + 0, /* tp_iternext */ + 0, /* tp_methods */ + 0, /* 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_new */ + 0, /* tp_free */ + 0, /* tp_is_gc */ + 0, /* tp_bases */ + 0, /* tp_mro */ + 0, /* tp_cache */ + 0, /* tp_subclasses */ + 0, /* tp_weaklist */ +#endif +#if PY_VERSION_HEX >= 0x02030000 + 0, /* tp_del */ +#endif +#if PY_VERSION_HEX >= 0x02060000 + 0, /* tp_version */ +#endif +#ifdef COUNT_ALLOCS + 0,0,0,0 /* tp_alloc -> tp_next */ +#endif + }; + swigpypacked_type = tmp; + type_init = 1; +#if PY_VERSION_HEX < 0x02020000 + swigpypacked_type.ob_type = &PyType_Type; +#else + if (PyType_Ready(&swigpypacked_type) < 0) + return NULL; +#endif + } + return &swigpypacked_type; +} + +SWIGRUNTIME PyObject * +SwigPyPacked_New(void *ptr, size_t size, swig_type_info *ty) +{ + SwigPyPacked *sobj = PyObject_NEW(SwigPyPacked, SwigPyPacked_type()); + if (sobj) { + void *pack = malloc(size); + if (pack) { + memcpy(pack, ptr, size); + sobj->pack = pack; + sobj->ty = ty; + sobj->size = size; + } else { + PyObject_DEL((PyObject *) sobj); + sobj = 0; + } + } + return (PyObject *) sobj; +} + +SWIGRUNTIME swig_type_info * +SwigPyPacked_UnpackData(PyObject *obj, void *ptr, size_t size) +{ + if (SwigPyPacked_Check(obj)) { + SwigPyPacked *sobj = (SwigPyPacked *)obj; + if (sobj->size != size) return 0; + memcpy(ptr, sobj->pack, size); + return sobj->ty; + } else { + return 0; + } +} + +/* ----------------------------------------------------------------------------- + * pointers/data manipulation + * ----------------------------------------------------------------------------- */ + +SWIGRUNTIMEINLINE PyObject * +_SWIG_This(void) +{ + return SWIG_Python_str_FromChar("this"); +} + +static PyObject *swig_this = NULL; + +SWIGRUNTIME PyObject * +SWIG_This(void) +{ + if (swig_this == NULL) + swig_this = _SWIG_This(); + return swig_this; +} + +/* #define SWIG_PYTHON_SLOW_GETSET_THIS */ + +/* TODO: I don't know how to implement the fast getset in Python 3 right now */ +#if PY_VERSION_HEX>=0x03000000 +#define SWIG_PYTHON_SLOW_GETSET_THIS +#endif + +SWIGRUNTIME SwigPyObject * +SWIG_Python_GetSwigThis(PyObject *pyobj) +{ + PyObject *obj; + + if (SwigPyObject_Check(pyobj)) + return (SwigPyObject *) pyobj; + +#ifdef SWIGPYTHON_BUILTIN + (void)obj; +# ifdef PyWeakref_CheckProxy + if (PyWeakref_CheckProxy(pyobj)) { + pyobj = PyWeakref_GET_OBJECT(pyobj); + if (pyobj && SwigPyObject_Check(pyobj)) + return (SwigPyObject*) pyobj; + } +# endif + return NULL; +#else + + obj = 0; + +#if (!defined(SWIG_PYTHON_SLOW_GETSET_THIS) && (PY_VERSION_HEX >= 0x02030000)) + if (PyInstance_Check(pyobj)) { + obj = _PyInstance_Lookup(pyobj, SWIG_This()); + } else { + PyObject **dictptr = _PyObject_GetDictPtr(pyobj); + if (dictptr != NULL) { + PyObject *dict = *dictptr; + obj = dict ? PyDict_GetItem(dict, SWIG_This()) : 0; + } else { +#ifdef PyWeakref_CheckProxy + if (PyWeakref_CheckProxy(pyobj)) { + PyObject *wobj = PyWeakref_GET_OBJECT(pyobj); + return wobj ? SWIG_Python_GetSwigThis(wobj) : 0; + } +#endif + obj = PyObject_GetAttr(pyobj,SWIG_This()); + if (obj) { + Py_DECREF(obj); + } else { + if (PyErr_Occurred()) PyErr_Clear(); + return 0; + } + } + } +#else + obj = PyObject_GetAttr(pyobj,SWIG_This()); + if (obj) { + Py_DECREF(obj); + } else { + if (PyErr_Occurred()) PyErr_Clear(); + return 0; + } +#endif + if (obj && !SwigPyObject_Check(obj)) { + /* a PyObject is called 'this', try to get the 'real this' + SwigPyObject from it */ + return SWIG_Python_GetSwigThis(obj); + } + return (SwigPyObject *)obj; +#endif +} + +/* Acquire a pointer value */ + +SWIGRUNTIME int +SWIG_Python_AcquirePtr(PyObject *obj, int own) { + if (own == SWIG_POINTER_OWN) { + SwigPyObject *sobj = SWIG_Python_GetSwigThis(obj); + if (sobj) { + int oldown = sobj->own; + sobj->own = own; + return oldown; + } + } + return 0; +} + +/* Convert a pointer value */ + +SWIGRUNTIME int +SWIG_Python_ConvertPtrAndOwn(PyObject *obj, void **ptr, swig_type_info *ty, int flags, int *own) { + int res; + SwigPyObject *sobj; + int implicit_conv = (flags & SWIG_POINTER_IMPLICIT_CONV) != 0; + + if (!obj) + return SWIG_ERROR; + if (obj == Py_None && !implicit_conv) { + if (ptr) + *ptr = 0; + return SWIG_OK; + } + + res = SWIG_ERROR; + + sobj = SWIG_Python_GetSwigThis(obj); + if (own) + *own = 0; + while (sobj) { + void *vptr = sobj->ptr; + if (ty) { + swig_type_info *to = sobj->ty; + if (to == ty) { + /* no type cast needed */ + if (ptr) *ptr = vptr; + break; + } else { + swig_cast_info *tc = SWIG_TypeCheck(to->name,ty); + if (!tc) { + sobj = (SwigPyObject *)sobj->next; + } else { + if (ptr) { + int newmemory = 0; + *ptr = SWIG_TypeCast(tc,vptr,&newmemory); + if (newmemory == SWIG_CAST_NEW_MEMORY) { + assert(own); /* badly formed typemap which will lead to a memory leak - it must set and use own to delete *ptr */ + if (own) + *own = *own | SWIG_CAST_NEW_MEMORY; + } + } + break; + } + } + } else { + if (ptr) *ptr = vptr; + break; + } + } + if (sobj) { + if (own) + *own = *own | sobj->own; + if (flags & SWIG_POINTER_DISOWN) { + sobj->own = 0; + } + res = SWIG_OK; + } else { + if (implicit_conv) { + SwigPyClientData *data = ty ? (SwigPyClientData *) ty->clientdata : 0; + if (data && !data->implicitconv) { + PyObject *klass = data->klass; + if (klass) { + PyObject *impconv; + data->implicitconv = 1; /* avoid recursion and call 'explicit' constructors*/ + impconv = SWIG_Python_CallFunctor(klass, obj); + data->implicitconv = 0; + if (PyErr_Occurred()) { + PyErr_Clear(); + impconv = 0; + } + if (impconv) { + SwigPyObject *iobj = SWIG_Python_GetSwigThis(impconv); + if (iobj) { + void *vptr; + res = SWIG_Python_ConvertPtrAndOwn((PyObject*)iobj, &vptr, ty, 0, 0); + if (SWIG_IsOK(res)) { + if (ptr) { + *ptr = vptr; + /* transfer the ownership to 'ptr' */ + iobj->own = 0; + res = SWIG_AddCast(res); + res = SWIG_AddNewMask(res); + } else { + res = SWIG_AddCast(res); + } + } + } + Py_DECREF(impconv); + } + } + } + } + if (!SWIG_IsOK(res) && obj == Py_None) { + if (ptr) + *ptr = 0; + if (PyErr_Occurred()) + PyErr_Clear(); + res = SWIG_OK; + } + } + return res; +} + +/* Convert a function ptr value */ + +SWIGRUNTIME int +SWIG_Python_ConvertFunctionPtr(PyObject *obj, void **ptr, swig_type_info *ty) { + if (!PyCFunction_Check(obj)) { + return SWIG_ConvertPtr(obj, ptr, ty, 0); + } else { + void *vptr = 0; + + /* here we get the method pointer for callbacks */ + const char *doc = (((PyCFunctionObject *)obj) -> m_ml -> ml_doc); + const char *desc = doc ? strstr(doc, "swig_ptr: ") : 0; + if (desc) + desc = ty ? SWIG_UnpackVoidPtr(desc + 10, &vptr, ty->name) : 0; + if (!desc) + return SWIG_ERROR; + if (ty) { + swig_cast_info *tc = SWIG_TypeCheck(desc,ty); + if (tc) { + int newmemory = 0; + *ptr = SWIG_TypeCast(tc,vptr,&newmemory); + assert(!newmemory); /* newmemory handling not yet implemented */ + } else { + return SWIG_ERROR; + } + } else { + *ptr = vptr; + } + return SWIG_OK; + } +} + +/* Convert a packed value value */ + +SWIGRUNTIME int +SWIG_Python_ConvertPacked(PyObject *obj, void *ptr, size_t sz, swig_type_info *ty) { + swig_type_info *to = SwigPyPacked_UnpackData(obj, ptr, sz); + if (!to) return SWIG_ERROR; + if (ty) { + if (to != ty) { + /* check type cast? */ + swig_cast_info *tc = SWIG_TypeCheck(to->name,ty); + if (!tc) return SWIG_ERROR; + } + } + return SWIG_OK; +} + +/* ----------------------------------------------------------------------------- + * Create a new pointer object + * ----------------------------------------------------------------------------- */ + +/* + Create a new instance object, without calling __init__, and set the + 'this' attribute. +*/ + +SWIGRUNTIME PyObject* +SWIG_Python_NewShadowInstance(SwigPyClientData *data, PyObject *swig_this) +{ +#if (PY_VERSION_HEX >= 0x02020000) + PyObject *inst = 0; + PyObject *newraw = data->newraw; + if (newraw) { + inst = PyObject_Call(newraw, data->newargs, NULL); + if (inst) { +#if !defined(SWIG_PYTHON_SLOW_GETSET_THIS) + PyObject **dictptr = _PyObject_GetDictPtr(inst); + if (dictptr != NULL) { + PyObject *dict = *dictptr; + if (dict == NULL) { + dict = PyDict_New(); + *dictptr = dict; + PyDict_SetItem(dict, SWIG_This(), swig_this); + } + } +#else + PyObject *key = SWIG_This(); + PyObject_SetAttr(inst, key, swig_this); +#endif + } + } else { +#if PY_VERSION_HEX >= 0x03000000 + inst = ((PyTypeObject*) data->newargs)->tp_new((PyTypeObject*) data->newargs, Py_None, Py_None); + if (inst) { + PyObject_SetAttr(inst, SWIG_This(), swig_this); + Py_TYPE(inst)->tp_flags &= ~Py_TPFLAGS_VALID_VERSION_TAG; + } +#else + PyObject *dict = PyDict_New(); + if (dict) { + PyDict_SetItem(dict, SWIG_This(), swig_this); + inst = PyInstance_NewRaw(data->newargs, dict); + Py_DECREF(dict); + } +#endif + } + return inst; +#else +#if (PY_VERSION_HEX >= 0x02010000) + PyObject *inst = 0; + PyObject *dict = PyDict_New(); + if (dict) { + PyDict_SetItem(dict, SWIG_This(), swig_this); + inst = PyInstance_NewRaw(data->newargs, dict); + Py_DECREF(dict); + } + return (PyObject *) inst; +#else + PyInstanceObject *inst = PyObject_NEW(PyInstanceObject, &PyInstance_Type); + if (inst == NULL) { + return NULL; + } + inst->in_class = (PyClassObject *)data->newargs; + Py_INCREF(inst->in_class); + inst->in_dict = PyDict_New(); + if (inst->in_dict == NULL) { + Py_DECREF(inst); + return NULL; + } +#ifdef Py_TPFLAGS_HAVE_WEAKREFS + inst->in_weakreflist = NULL; +#endif +#ifdef Py_TPFLAGS_GC + PyObject_GC_Init(inst); +#endif + PyDict_SetItem(inst->in_dict, SWIG_This(), swig_this); + return (PyObject *) inst; +#endif +#endif +} + +SWIGRUNTIME void +SWIG_Python_SetSwigThis(PyObject *inst, PyObject *swig_this) +{ + PyObject *dict; +#if (PY_VERSION_HEX >= 0x02020000) && !defined(SWIG_PYTHON_SLOW_GETSET_THIS) + PyObject **dictptr = _PyObject_GetDictPtr(inst); + if (dictptr != NULL) { + dict = *dictptr; + if (dict == NULL) { + dict = PyDict_New(); + *dictptr = dict; + } + PyDict_SetItem(dict, SWIG_This(), swig_this); + return; + } +#endif + dict = PyObject_GetAttrString(inst, (char*)"__dict__"); + PyDict_SetItem(dict, SWIG_This(), swig_this); + Py_DECREF(dict); +} + + +SWIGINTERN PyObject * +SWIG_Python_InitShadowInstance(PyObject *args) { + PyObject *obj[2]; + if (!SWIG_Python_UnpackTuple(args, "swiginit", 2, 2, obj)) { + return NULL; + } else { + SwigPyObject *sthis = SWIG_Python_GetSwigThis(obj[0]); + if (sthis) { + SwigPyObject_append((PyObject*) sthis, obj[1]); + } else { + SWIG_Python_SetSwigThis(obj[0], obj[1]); + } + return SWIG_Py_Void(); + } +} + +/* Create a new pointer object */ + +SWIGRUNTIME PyObject * +SWIG_Python_NewPointerObj(PyObject *self, void *ptr, swig_type_info *type, int flags) { + SwigPyClientData *clientdata; + PyObject * robj; + int own; + + if (!ptr) + return SWIG_Py_Void(); + + clientdata = type ? (SwigPyClientData *)(type->clientdata) : 0; + own = (flags & SWIG_POINTER_OWN) ? SWIG_POINTER_OWN : 0; + if (clientdata && clientdata->pytype) { + SwigPyObject *newobj; + if (flags & SWIG_BUILTIN_TP_INIT) { + newobj = (SwigPyObject*) self; + if (newobj->ptr) { + PyObject *next_self = clientdata->pytype->tp_alloc(clientdata->pytype, 0); + while (newobj->next) + newobj = (SwigPyObject *) newobj->next; + newobj->next = next_self; + newobj = (SwigPyObject *)next_self; + } + } else { + newobj = PyObject_New(SwigPyObject, clientdata->pytype); + } + if (newobj) { + newobj->ptr = ptr; + newobj->ty = type; + newobj->own = own; + newobj->next = 0; +#ifdef SWIGPYTHON_BUILTIN + newobj->dict = 0; +#endif + return (PyObject*) newobj; + } + return SWIG_Py_Void(); + } + + assert(!(flags & SWIG_BUILTIN_TP_INIT)); + + robj = SwigPyObject_New(ptr, type, own); + if (robj && clientdata && !(flags & SWIG_POINTER_NOSHADOW)) { + PyObject *inst = SWIG_Python_NewShadowInstance(clientdata, robj); + Py_DECREF(robj); + robj = inst; + } + return robj; +} + +/* Create a new packed object */ + +SWIGRUNTIMEINLINE PyObject * +SWIG_Python_NewPackedObj(void *ptr, size_t sz, swig_type_info *type) { + return ptr ? SwigPyPacked_New((void *) ptr, sz, type) : SWIG_Py_Void(); +} + +/* -----------------------------------------------------------------------------* + * Get type list + * -----------------------------------------------------------------------------*/ + +#ifdef SWIG_LINK_RUNTIME +void *SWIG_ReturnGlobalTypeList(void *); +#endif + +SWIGRUNTIME swig_module_info * +SWIG_Python_GetModule(void *SWIGUNUSEDPARM(clientdata)) { + static void *type_pointer = (void *)0; + /* first check if module already created */ + if (!type_pointer) { +#ifdef SWIG_LINK_RUNTIME + type_pointer = SWIG_ReturnGlobalTypeList((void *)0); +#else +# ifdef SWIGPY_USE_CAPSULE + type_pointer = PyCapsule_Import(SWIGPY_CAPSULE_NAME, 0); +# else + type_pointer = PyCObject_Import((char*)"swig_runtime_data" SWIG_RUNTIME_VERSION, + (char*)"type_pointer" SWIG_TYPE_TABLE_NAME); +# endif + if (PyErr_Occurred()) { + PyErr_Clear(); + type_pointer = (void *)0; + } +#endif + } + return (swig_module_info *) type_pointer; +} + +#if PY_MAJOR_VERSION < 2 +/* PyModule_AddObject function was introduced in Python 2.0. The following function + is copied out of Python/modsupport.c in python version 2.3.4 */ +SWIGINTERN int +PyModule_AddObject(PyObject *m, char *name, PyObject *o) +{ + PyObject *dict; + if (!PyModule_Check(m)) { + PyErr_SetString(PyExc_TypeError, + "PyModule_AddObject() needs module as first arg"); + return SWIG_ERROR; + } + if (!o) { + PyErr_SetString(PyExc_TypeError, + "PyModule_AddObject() needs non-NULL value"); + return SWIG_ERROR; + } + + dict = PyModule_GetDict(m); + if (dict == NULL) { + /* Internal error -- modules must have a dict! */ + PyErr_Format(PyExc_SystemError, "module '%s' has no __dict__", + PyModule_GetName(m)); + return SWIG_ERROR; + } + if (PyDict_SetItemString(dict, name, o)) + return SWIG_ERROR; + Py_DECREF(o); + return SWIG_OK; +} +#endif + +SWIGRUNTIME void +#ifdef SWIGPY_USE_CAPSULE +SWIG_Python_DestroyModule(PyObject *obj) +#else +SWIG_Python_DestroyModule(void *vptr) +#endif +{ +#ifdef SWIGPY_USE_CAPSULE + swig_module_info *swig_module = (swig_module_info *) PyCapsule_GetPointer(obj, SWIGPY_CAPSULE_NAME); +#else + swig_module_info *swig_module = (swig_module_info *) vptr; +#endif + swig_type_info **types = swig_module->types; + size_t i; + for (i =0; i < swig_module->size; ++i) { + swig_type_info *ty = types[i]; + if (ty->owndata) { + SwigPyClientData *data = (SwigPyClientData *) ty->clientdata; + if (data) SwigPyClientData_Del(data); + } + } + Py_DECREF(SWIG_This()); + swig_this = NULL; +} + +SWIGRUNTIME void +SWIG_Python_SetModule(swig_module_info *swig_module) { +#if PY_VERSION_HEX >= 0x03000000 + /* Add a dummy module object into sys.modules */ + PyObject *module = PyImport_AddModule((char*)"swig_runtime_data" SWIG_RUNTIME_VERSION); +#else + static PyMethodDef swig_empty_runtime_method_table[] = { {NULL, NULL, 0, NULL} }; /* Sentinel */ + PyObject *module = Py_InitModule((char*)"swig_runtime_data" SWIG_RUNTIME_VERSION, swig_empty_runtime_method_table); +#endif +#ifdef SWIGPY_USE_CAPSULE + PyObject *pointer = PyCapsule_New((void *) swig_module, SWIGPY_CAPSULE_NAME, SWIG_Python_DestroyModule); + if (pointer && module) { + PyModule_AddObject(module, (char*)"type_pointer_capsule" SWIG_TYPE_TABLE_NAME, pointer); + } else { + Py_XDECREF(pointer); + } +#else + PyObject *pointer = PyCObject_FromVoidPtr((void *) swig_module, SWIG_Python_DestroyModule); + if (pointer && module) { + PyModule_AddObject(module, (char*)"type_pointer" SWIG_TYPE_TABLE_NAME, pointer); + } else { + Py_XDECREF(pointer); + } +#endif +} + +/* The python cached type query */ +SWIGRUNTIME PyObject * +SWIG_Python_TypeCache(void) { + static PyObject *SWIG_STATIC_POINTER(cache) = PyDict_New(); + return cache; +} + +SWIGRUNTIME swig_type_info * +SWIG_Python_TypeQuery(const char *type) +{ + PyObject *cache = SWIG_Python_TypeCache(); + PyObject *key = SWIG_Python_str_FromChar(type); + PyObject *obj = PyDict_GetItem(cache, key); + swig_type_info *descriptor; + if (obj) { +#ifdef SWIGPY_USE_CAPSULE + descriptor = (swig_type_info *) PyCapsule_GetPointer(obj, NULL); +#else + descriptor = (swig_type_info *) PyCObject_AsVoidPtr(obj); +#endif + } else { + swig_module_info *swig_module = SWIG_GetModule(0); + descriptor = SWIG_TypeQueryModule(swig_module, swig_module, type); + if (descriptor) { +#ifdef SWIGPY_USE_CAPSULE + obj = PyCapsule_New((void*) descriptor, NULL, NULL); +#else + obj = PyCObject_FromVoidPtr(descriptor, NULL); +#endif + PyDict_SetItem(cache, key, obj); + Py_DECREF(obj); + } + } + Py_DECREF(key); + return descriptor; +} + +/* + For backward compatibility only +*/ +#define SWIG_POINTER_EXCEPTION 0 +#define SWIG_arg_fail(arg) SWIG_Python_ArgFail(arg) +#define SWIG_MustGetPtr(p, type, argnum, flags) SWIG_Python_MustGetPtr(p, type, argnum, flags) + +SWIGRUNTIME int +SWIG_Python_AddErrMesg(const char* mesg, int infront) +{ + if (PyErr_Occurred()) { + PyObject *type = 0; + PyObject *value = 0; + PyObject *traceback = 0; + PyErr_Fetch(&type, &value, &traceback); + if (value) { + char *tmp; + PyObject *old_str = PyObject_Str(value); + Py_XINCREF(type); + PyErr_Clear(); + if (infront) { + PyErr_Format(type, "%s %s", mesg, tmp = SWIG_Python_str_AsChar(old_str)); + } else { + PyErr_Format(type, "%s %s", tmp = SWIG_Python_str_AsChar(old_str), mesg); + } + SWIG_Python_str_DelForPy3(tmp); + Py_DECREF(old_str); + } + return 1; + } else { + return 0; + } +} + +SWIGRUNTIME int +SWIG_Python_ArgFail(int argnum) +{ + if (PyErr_Occurred()) { + /* add information about failing argument */ + char mesg[256]; + PyOS_snprintf(mesg, sizeof(mesg), "argument number %d:", argnum); + return SWIG_Python_AddErrMesg(mesg, 1); + } else { + return 0; + } +} + +SWIGRUNTIMEINLINE const char * +SwigPyObject_GetDesc(PyObject *self) +{ + SwigPyObject *v = (SwigPyObject *)self; + swig_type_info *ty = v ? v->ty : 0; + return ty ? ty->str : ""; +} + +SWIGRUNTIME void +SWIG_Python_TypeError(const char *type, PyObject *obj) +{ + if (type) { +#if defined(SWIG_COBJECT_TYPES) + if (obj && SwigPyObject_Check(obj)) { + const char *otype = (const char *) SwigPyObject_GetDesc(obj); + if (otype) { + PyErr_Format(PyExc_TypeError, "a '%s' is expected, 'SwigPyObject(%s)' is received", + type, otype); + return; + } + } else +#endif + { + const char *otype = (obj ? obj->ob_type->tp_name : 0); + if (otype) { + PyObject *str = PyObject_Str(obj); + const char *cstr = str ? SWIG_Python_str_AsChar(str) : 0; + if (cstr) { + PyErr_Format(PyExc_TypeError, "a '%s' is expected, '%s(%s)' is received", + type, otype, cstr); + SWIG_Python_str_DelForPy3(cstr); + } else { + PyErr_Format(PyExc_TypeError, "a '%s' is expected, '%s' is received", + type, otype); + } + Py_XDECREF(str); + return; + } + } + PyErr_Format(PyExc_TypeError, "a '%s' is expected", type); + } else { + PyErr_Format(PyExc_TypeError, "unexpected type is received"); + } +} + + +/* Convert a pointer value, signal an exception on a type mismatch */ +SWIGRUNTIME void * +SWIG_Python_MustGetPtr(PyObject *obj, swig_type_info *ty, int SWIGUNUSEDPARM(argnum), int flags) { + void *result; + if (SWIG_Python_ConvertPtr(obj, &result, ty, flags) == -1) { + PyErr_Clear(); +#if SWIG_POINTER_EXCEPTION + if (flags) { + SWIG_Python_TypeError(SWIG_TypePrettyName(ty), obj); + SWIG_Python_ArgFail(argnum); + } +#endif + } + return result; +} + +#ifdef SWIGPYTHON_BUILTIN +SWIGRUNTIME int +SWIG_Python_NonDynamicSetAttr(PyObject *obj, PyObject *name, PyObject *value) { + PyTypeObject *tp = obj->ob_type; + PyObject *descr; + PyObject *encoded_name; + descrsetfunc f; + int res = -1; + +# ifdef Py_USING_UNICODE + if (PyString_Check(name)) { + name = PyUnicode_Decode(PyString_AsString(name), PyString_Size(name), NULL, NULL); + if (!name) + return -1; + } else if (!PyUnicode_Check(name)) +# else + if (!PyString_Check(name)) +# endif + { + PyErr_Format(PyExc_TypeError, "attribute name must be string, not '%.200s'", name->ob_type->tp_name); + return -1; + } else { + Py_INCREF(name); + } + + if (!tp->tp_dict) { + if (PyType_Ready(tp) < 0) + goto done; + } + + descr = _PyType_Lookup(tp, name); + f = NULL; + if (descr != NULL) + f = descr->ob_type->tp_descr_set; + if (!f) { + if (PyString_Check(name)) { + encoded_name = name; + Py_INCREF(name); + } else { + encoded_name = PyUnicode_AsUTF8String(name); + } + PyErr_Format(PyExc_AttributeError, "'%.100s' object has no attribute '%.200s'", tp->tp_name, PyString_AsString(encoded_name)); + Py_DECREF(encoded_name); + } else { + res = f(descr, obj, value); + } + + done: + Py_DECREF(name); + return res; +} +#endif + + +#ifdef __cplusplus +} +#endif + + + +#define SWIG_exception_fail(code, msg) do { SWIG_Error(code, msg); SWIG_fail; } while(0) + +#define SWIG_contract_assert(expr, msg) if (!(expr)) { SWIG_Error(SWIG_RuntimeError, msg); SWIG_fail; } else + + + +/* -------- TYPES TABLE (BEGIN) -------- */ + +#define SWIGTYPE_p_ESLconnection swig_types[0] +#define SWIGTYPE_p_ESLevent swig_types[1] +#define SWIGTYPE_p_char swig_types[2] +#define SWIGTYPE_p_esl_event_t swig_types[3] +#define SWIGTYPE_p_esl_priority_t swig_types[4] +static swig_type_info *swig_types[6]; +static swig_module_info swig_module = {swig_types, 5, 0, 0, 0, 0}; +#define SWIG_TypeQuery(name) SWIG_TypeQueryModule(&swig_module, &swig_module, name) +#define SWIG_MangledTypeQuery(name) SWIG_MangledTypeQueryModule(&swig_module, &swig_module, name) + +/* -------- TYPES TABLE (END) -------- */ + +#if (PY_VERSION_HEX <= 0x02000000) +# if !defined(SWIG_PYTHON_CLASSIC) +# error "This python version requires swig to be run with the '-classic' option" +# endif +#endif + +/*----------------------------------------------- + @(target):= _ESL.so + ------------------------------------------------*/ +#if PY_VERSION_HEX >= 0x03000000 +# define SWIG_init PyInit__ESL + +#else +# define SWIG_init init_ESL + +#endif +#define SWIG_name "_ESL" + +#define SWIGVERSION 0x030002 +#define SWIG_VERSION SWIGVERSION + + +#define SWIG_as_voidptr(a) const_cast< void * >(static_cast< const void * >(a)) +#define SWIG_as_voidptrptr(a) ((void)SWIG_as_voidptr(*a),reinterpret_cast< void** >(a)) + + +#include + + +namespace swig { + class SwigPtr_PyObject { + protected: + PyObject *_obj; + + public: + SwigPtr_PyObject() :_obj(0) + { + } + + SwigPtr_PyObject(const SwigPtr_PyObject& item) : _obj(item._obj) + { + Py_XINCREF(_obj); + } + + SwigPtr_PyObject(PyObject *obj, bool initial_ref = true) :_obj(obj) + { + if (initial_ref) { + Py_XINCREF(_obj); + } + } + + SwigPtr_PyObject & operator=(const SwigPtr_PyObject& item) + { + Py_XINCREF(item._obj); + Py_XDECREF(_obj); + _obj = item._obj; + return *this; + } + + ~SwigPtr_PyObject() + { + Py_XDECREF(_obj); + } + + operator PyObject *() const + { + return _obj; + } + + PyObject *operator->() const + { + return _obj; + } + }; +} + + +namespace swig { + struct SwigVar_PyObject : SwigPtr_PyObject { + SwigVar_PyObject(PyObject* obj = 0) : SwigPtr_PyObject(obj, false) { } + + SwigVar_PyObject & operator = (PyObject* obj) + { + Py_XDECREF(_obj); + _obj = obj; + return *this; + } + }; +} + + +#include "esl.h" +#include "esl_oop.h" + + +SWIGINTERN swig_type_info* +SWIG_pchar_descriptor(void) +{ + static int init = 0; + static swig_type_info* info = 0; + if (!init) { + info = SWIG_TypeQuery("_p_char"); + init = 1; + } + return info; +} + + +SWIGINTERN int +SWIG_AsCharPtrAndSize(PyObject *obj, char** cptr, size_t* psize, int *alloc) +{ +#if PY_VERSION_HEX>=0x03000000 + if (PyUnicode_Check(obj)) +#else + if (PyString_Check(obj)) +#endif + { + char *cstr; Py_ssize_t len; +#if PY_VERSION_HEX>=0x03000000 + if (!alloc && cptr) { + /* We can't allow converting without allocation, since the internal + representation of string in Python 3 is UCS-2/UCS-4 but we require + a UTF-8 representation. + TODO(bhy) More detailed explanation */ + return SWIG_RuntimeError; + } + obj = PyUnicode_AsUTF8String(obj); + PyBytes_AsStringAndSize(obj, &cstr, &len); + if(alloc) *alloc = SWIG_NEWOBJ; +#else + PyString_AsStringAndSize(obj, &cstr, &len); +#endif + if (cptr) { + if (alloc) { + /* + In python the user should not be able to modify the inner + string representation. To warranty that, if you define + SWIG_PYTHON_SAFE_CSTRINGS, a new/copy of the python string + buffer is always returned. + + The default behavior is just to return the pointer value, + so, be careful. + */ +#if defined(SWIG_PYTHON_SAFE_CSTRINGS) + if (*alloc != SWIG_OLDOBJ) +#else + if (*alloc == SWIG_NEWOBJ) +#endif + { + *cptr = reinterpret_cast< char* >(memcpy((new char[len + 1]), cstr, sizeof(char)*(len + 1))); + *alloc = SWIG_NEWOBJ; + } + else { + *cptr = cstr; + *alloc = SWIG_OLDOBJ; + } + } else { + #if PY_VERSION_HEX>=0x03000000 + assert(0); /* Should never reach here in Python 3 */ + #endif + *cptr = SWIG_Python_str_AsChar(obj); + } + } + if (psize) *psize = len + 1; +#if PY_VERSION_HEX>=0x03000000 + Py_XDECREF(obj); +#endif + return SWIG_OK; + } else { + swig_type_info* pchar_descriptor = SWIG_pchar_descriptor(); + if (pchar_descriptor) { + void* vptr = 0; + if (SWIG_ConvertPtr(obj, &vptr, pchar_descriptor, 0) == SWIG_OK) { + if (cptr) *cptr = (char *) vptr; + if (psize) *psize = vptr ? (strlen((char *)vptr) + 1) : 0; + if (alloc) *alloc = SWIG_OLDOBJ; + return SWIG_OK; + } + } + } + return SWIG_TypeError; +} + + + + + +SWIGINTERNINLINE PyObject * +SWIG_FromCharPtrAndSize(const char* carray, size_t size) +{ + if (carray) { + if (size > INT_MAX) { + swig_type_info* pchar_descriptor = SWIG_pchar_descriptor(); + return pchar_descriptor ? + SWIG_InternalNewPointerObj(const_cast< char * >(carray), pchar_descriptor, 0) : SWIG_Py_Void(); + } else { +#if PY_VERSION_HEX >= 0x03000000 +#if PY_VERSION_HEX >= 0x03010000 + return PyUnicode_DecodeUTF8(carray, static_cast< int >(size), "surrogateescape"); +#else + return PyUnicode_FromStringAndSize(carray, static_cast< int >(size)); +#endif +#else + return PyString_FromStringAndSize(carray, static_cast< int >(size)); +#endif + } + } else { + return SWIG_Py_Void(); + } +} + + +SWIGINTERNINLINE PyObject * +SWIG_FromCharPtr(const char *cptr) +{ + return SWIG_FromCharPtrAndSize(cptr, (cptr ? strlen(cptr) : 0)); +} + + +#include +#if !defined(SWIG_NO_LLONG_MAX) +# if !defined(LLONG_MAX) && defined(__GNUC__) && defined (__LONG_LONG_MAX__) +# define LLONG_MAX __LONG_LONG_MAX__ +# define LLONG_MIN (-LLONG_MAX - 1LL) +# define ULLONG_MAX (LLONG_MAX * 2ULL + 1ULL) +# endif +#endif + + +SWIGINTERN int +SWIG_AsVal_double (PyObject *obj, double *val) +{ + int res = SWIG_TypeError; + if (PyFloat_Check(obj)) { + if (val) *val = PyFloat_AsDouble(obj); + return SWIG_OK; + } else if (PyInt_Check(obj)) { + if (val) *val = PyInt_AsLong(obj); + return SWIG_OK; + } else if (PyLong_Check(obj)) { + double v = PyLong_AsDouble(obj); + if (!PyErr_Occurred()) { + if (val) *val = v; + return SWIG_OK; + } else { + PyErr_Clear(); + } + } +#ifdef SWIG_PYTHON_CAST_MODE + { + int dispatch = 0; + double d = PyFloat_AsDouble(obj); + if (!PyErr_Occurred()) { + if (val) *val = d; + return SWIG_AddCast(SWIG_OK); + } else { + PyErr_Clear(); + } + if (!dispatch) { + long v = PyLong_AsLong(obj); + if (!PyErr_Occurred()) { + if (val) *val = v; + return SWIG_AddCast(SWIG_AddCast(SWIG_OK)); + } else { + PyErr_Clear(); + } + } + } +#endif + return res; +} + + +#include + + +#include + + +SWIGINTERNINLINE int +SWIG_CanCastAsInteger(double *d, double min, double max) { + double x = *d; + if ((min <= x && x <= max)) { + double fx = floor(x); + double cx = ceil(x); + double rd = ((x - fx) < 0.5) ? fx : cx; /* simple rint */ + if ((errno == EDOM) || (errno == ERANGE)) { + errno = 0; + } else { + double summ, reps, diff; + if (rd < x) { + diff = x - rd; + } else if (rd > x) { + diff = rd - x; + } else { + return 1; + } + summ = rd + x; + reps = diff/summ; + if (reps < 8*DBL_EPSILON) { + *d = rd; + return 1; + } + } + } + return 0; +} + + +SWIGINTERN int +SWIG_AsVal_long (PyObject *obj, long* val) +{ + if (PyInt_Check(obj)) { + if (val) *val = PyInt_AsLong(obj); + return SWIG_OK; + } else if (PyLong_Check(obj)) { + long v = PyLong_AsLong(obj); + if (!PyErr_Occurred()) { + if (val) *val = v; + return SWIG_OK; + } else { + PyErr_Clear(); + } + } +#ifdef SWIG_PYTHON_CAST_MODE + { + int dispatch = 0; + long v = PyInt_AsLong(obj); + if (!PyErr_Occurred()) { + if (val) *val = v; + return SWIG_AddCast(SWIG_OK); + } else { + PyErr_Clear(); + } + if (!dispatch) { + double d; + int res = SWIG_AddCast(SWIG_AsVal_double (obj,&d)); + if (SWIG_IsOK(res) && SWIG_CanCastAsInteger(&d, LONG_MIN, LONG_MAX)) { + if (val) *val = (long)(d); + return res; + } + } + } +#endif + return SWIG_TypeError; +} + + +SWIGINTERN int +SWIG_AsVal_int (PyObject * obj, int *val) +{ + long v; + int res = SWIG_AsVal_long (obj, &v); + if (SWIG_IsOK(res)) { + if ((v < INT_MIN || v > INT_MAX)) { + return SWIG_OverflowError; + } else { + if (val) *val = static_cast< int >(v); + } + } + return res; +} + + +SWIGINTERNINLINE PyObject* + SWIG_From_int (int value) +{ + return PyInt_FromLong((long) value); +} + + +SWIGINTERNINLINE PyObject* + SWIG_From_bool (bool value) +{ + return PyBool_FromLong(value ? 1 : 0); +} + +#ifdef __cplusplus +extern "C" { +#endif +SWIGINTERN PyObject *_wrap_ESLevent_event_set(PyObject *SWIGUNUSEDPARM(self), PyObject *args) { + PyObject *resultobj = 0; + ESLevent *arg1 = (ESLevent *) 0 ; + esl_event_t *arg2 = (esl_event_t *) 0 ; + void *argp1 = 0 ; + int res1 = 0 ; + void *argp2 = 0 ; + int res2 = 0 ; + PyObject * obj0 = 0 ; + PyObject * obj1 = 0 ; + + if (!PyArg_ParseTuple(args,(char *)"OO:ESLevent_event_set",&obj0,&obj1)) SWIG_fail; + res1 = SWIG_ConvertPtr(obj0, &argp1,SWIGTYPE_p_ESLevent, 0 | 0 ); + if (!SWIG_IsOK(res1)) { + SWIG_exception_fail(SWIG_ArgError(res1), "in method '" "ESLevent_event_set" "', argument " "1"" of type '" "ESLevent *""'"); + } + arg1 = reinterpret_cast< ESLevent * >(argp1); + res2 = SWIG_ConvertPtr(obj1, &argp2,SWIGTYPE_p_esl_event_t, SWIG_POINTER_DISOWN | 0 ); + if (!SWIG_IsOK(res2)) { + SWIG_exception_fail(SWIG_ArgError(res2), "in method '" "ESLevent_event_set" "', argument " "2"" of type '" "esl_event_t *""'"); + } + arg2 = reinterpret_cast< esl_event_t * >(argp2); + { + SWIG_PYTHON_THREAD_BEGIN_ALLOW; + if (arg1) (arg1)->event = arg2; + SWIG_PYTHON_THREAD_END_ALLOW; + } + resultobj = SWIG_Py_Void(); + return resultobj; +fail: + return NULL; +} + + +SWIGINTERN PyObject *_wrap_ESLevent_event_get(PyObject *SWIGUNUSEDPARM(self), PyObject *args) { + PyObject *resultobj = 0; + ESLevent *arg1 = (ESLevent *) 0 ; + void *argp1 = 0 ; + int res1 = 0 ; + PyObject * obj0 = 0 ; + esl_event_t *result = 0 ; + + if (!PyArg_ParseTuple(args,(char *)"O:ESLevent_event_get",&obj0)) SWIG_fail; + res1 = SWIG_ConvertPtr(obj0, &argp1,SWIGTYPE_p_ESLevent, 0 | 0 ); + if (!SWIG_IsOK(res1)) { + SWIG_exception_fail(SWIG_ArgError(res1), "in method '" "ESLevent_event_get" "', argument " "1"" of type '" "ESLevent *""'"); + } + arg1 = reinterpret_cast< ESLevent * >(argp1); + { + SWIG_PYTHON_THREAD_BEGIN_ALLOW; + result = (esl_event_t *) ((arg1)->event); + SWIG_PYTHON_THREAD_END_ALLOW; + } + resultobj = SWIG_NewPointerObj(SWIG_as_voidptr(result), SWIGTYPE_p_esl_event_t, 0 | 0 ); + return resultobj; +fail: + return NULL; +} + + +SWIGINTERN PyObject *_wrap_ESLevent_serialized_string_set(PyObject *SWIGUNUSEDPARM(self), PyObject *args) { + PyObject *resultobj = 0; + ESLevent *arg1 = (ESLevent *) 0 ; + char *arg2 = (char *) 0 ; + void *argp1 = 0 ; + int res1 = 0 ; + int res2 ; + char *buf2 = 0 ; + int alloc2 = 0 ; + PyObject * obj0 = 0 ; + PyObject * obj1 = 0 ; + + if (!PyArg_ParseTuple(args,(char *)"OO:ESLevent_serialized_string_set",&obj0,&obj1)) SWIG_fail; + res1 = SWIG_ConvertPtr(obj0, &argp1,SWIGTYPE_p_ESLevent, 0 | 0 ); + if (!SWIG_IsOK(res1)) { + SWIG_exception_fail(SWIG_ArgError(res1), "in method '" "ESLevent_serialized_string_set" "', argument " "1"" of type '" "ESLevent *""'"); + } + arg1 = reinterpret_cast< ESLevent * >(argp1); + res2 = SWIG_AsCharPtrAndSize(obj1, &buf2, NULL, &alloc2); + if (!SWIG_IsOK(res2)) { + SWIG_exception_fail(SWIG_ArgError(res2), "in method '" "ESLevent_serialized_string_set" "', argument " "2"" of type '" "char *""'"); + } + arg2 = reinterpret_cast< char * >(buf2); + { + SWIG_PYTHON_THREAD_BEGIN_ALLOW; + if (arg1->serialized_string) delete[] arg1->serialized_string; + if (arg2) { + size_t size = strlen(reinterpret_cast< const char * >(arg2)) + 1; + arg1->serialized_string = (char *)reinterpret_cast< char* >(memcpy((new char[size]), reinterpret_cast< const char * >(arg2), sizeof(char)*(size))); + } else { + arg1->serialized_string = 0; + } + SWIG_PYTHON_THREAD_END_ALLOW; + } + resultobj = SWIG_Py_Void(); + if (alloc2 == SWIG_NEWOBJ) delete[] buf2; + return resultobj; +fail: + if (alloc2 == SWIG_NEWOBJ) delete[] buf2; + return NULL; +} + + +SWIGINTERN PyObject *_wrap_ESLevent_serialized_string_get(PyObject *SWIGUNUSEDPARM(self), PyObject *args) { + PyObject *resultobj = 0; + ESLevent *arg1 = (ESLevent *) 0 ; + void *argp1 = 0 ; + int res1 = 0 ; + PyObject * obj0 = 0 ; + char *result = 0 ; + + if (!PyArg_ParseTuple(args,(char *)"O:ESLevent_serialized_string_get",&obj0)) SWIG_fail; + res1 = SWIG_ConvertPtr(obj0, &argp1,SWIGTYPE_p_ESLevent, 0 | 0 ); + if (!SWIG_IsOK(res1)) { + SWIG_exception_fail(SWIG_ArgError(res1), "in method '" "ESLevent_serialized_string_get" "', argument " "1"" of type '" "ESLevent *""'"); + } + arg1 = reinterpret_cast< ESLevent * >(argp1); + { + SWIG_PYTHON_THREAD_BEGIN_ALLOW; + result = (char *) ((arg1)->serialized_string); + SWIG_PYTHON_THREAD_END_ALLOW; + } + resultobj = SWIG_FromCharPtr((const char *)result); + return resultobj; +fail: + return NULL; +} + + +SWIGINTERN PyObject *_wrap_ESLevent_mine_set(PyObject *SWIGUNUSEDPARM(self), PyObject *args) { + PyObject *resultobj = 0; + ESLevent *arg1 = (ESLevent *) 0 ; + int arg2 ; + void *argp1 = 0 ; + int res1 = 0 ; + int val2 ; + int ecode2 = 0 ; + PyObject * obj0 = 0 ; + PyObject * obj1 = 0 ; + + if (!PyArg_ParseTuple(args,(char *)"OO:ESLevent_mine_set",&obj0,&obj1)) SWIG_fail; + res1 = SWIG_ConvertPtr(obj0, &argp1,SWIGTYPE_p_ESLevent, 0 | 0 ); + if (!SWIG_IsOK(res1)) { + SWIG_exception_fail(SWIG_ArgError(res1), "in method '" "ESLevent_mine_set" "', argument " "1"" of type '" "ESLevent *""'"); + } + arg1 = reinterpret_cast< ESLevent * >(argp1); + ecode2 = SWIG_AsVal_int(obj1, &val2); + if (!SWIG_IsOK(ecode2)) { + SWIG_exception_fail(SWIG_ArgError(ecode2), "in method '" "ESLevent_mine_set" "', argument " "2"" of type '" "int""'"); + } + arg2 = static_cast< int >(val2); + { + SWIG_PYTHON_THREAD_BEGIN_ALLOW; + if (arg1) (arg1)->mine = arg2; + SWIG_PYTHON_THREAD_END_ALLOW; + } + resultobj = SWIG_Py_Void(); + return resultobj; +fail: + return NULL; +} + + +SWIGINTERN PyObject *_wrap_ESLevent_mine_get(PyObject *SWIGUNUSEDPARM(self), PyObject *args) { + PyObject *resultobj = 0; + ESLevent *arg1 = (ESLevent *) 0 ; + void *argp1 = 0 ; + int res1 = 0 ; + PyObject * obj0 = 0 ; + int result; + + if (!PyArg_ParseTuple(args,(char *)"O:ESLevent_mine_get",&obj0)) SWIG_fail; + res1 = SWIG_ConvertPtr(obj0, &argp1,SWIGTYPE_p_ESLevent, 0 | 0 ); + if (!SWIG_IsOK(res1)) { + SWIG_exception_fail(SWIG_ArgError(res1), "in method '" "ESLevent_mine_get" "', argument " "1"" of type '" "ESLevent *""'"); + } + arg1 = reinterpret_cast< ESLevent * >(argp1); + { + SWIG_PYTHON_THREAD_BEGIN_ALLOW; + result = (int) ((arg1)->mine); + SWIG_PYTHON_THREAD_END_ALLOW; + } + resultobj = SWIG_From_int(static_cast< int >(result)); + return resultobj; +fail: + return NULL; +} + + +SWIGINTERN PyObject *_wrap_new_ESLevent__SWIG_0(PyObject *SWIGUNUSEDPARM(self), PyObject *args) { + PyObject *resultobj = 0; + char *arg1 = (char *) 0 ; + char *arg2 = (char *) NULL ; + int res1 ; + char *buf1 = 0 ; + int alloc1 = 0 ; + int res2 ; + char *buf2 = 0 ; + int alloc2 = 0 ; + PyObject * obj0 = 0 ; + PyObject * obj1 = 0 ; + ESLevent *result = 0 ; + + if (!PyArg_ParseTuple(args,(char *)"O|O:new_ESLevent",&obj0,&obj1)) SWIG_fail; + res1 = SWIG_AsCharPtrAndSize(obj0, &buf1, NULL, &alloc1); + if (!SWIG_IsOK(res1)) { + SWIG_exception_fail(SWIG_ArgError(res1), "in method '" "new_ESLevent" "', argument " "1"" of type '" "char const *""'"); + } + arg1 = reinterpret_cast< char * >(buf1); + if (obj1) { + res2 = SWIG_AsCharPtrAndSize(obj1, &buf2, NULL, &alloc2); + if (!SWIG_IsOK(res2)) { + SWIG_exception_fail(SWIG_ArgError(res2), "in method '" "new_ESLevent" "', argument " "2"" of type '" "char const *""'"); + } + arg2 = reinterpret_cast< char * >(buf2); + } + { + SWIG_PYTHON_THREAD_BEGIN_ALLOW; + result = (ESLevent *)new ESLevent((char const *)arg1,(char const *)arg2); + SWIG_PYTHON_THREAD_END_ALLOW; + } + resultobj = SWIG_NewPointerObj(SWIG_as_voidptr(result), SWIGTYPE_p_ESLevent, SWIG_POINTER_NEW | 0 ); + if (alloc1 == SWIG_NEWOBJ) delete[] buf1; + if (alloc2 == SWIG_NEWOBJ) delete[] buf2; + return resultobj; +fail: + if (alloc1 == SWIG_NEWOBJ) delete[] buf1; + if (alloc2 == SWIG_NEWOBJ) delete[] buf2; + return NULL; +} + + +SWIGINTERN PyObject *_wrap_new_ESLevent__SWIG_1(PyObject *SWIGUNUSEDPARM(self), PyObject *args) { + PyObject *resultobj = 0; + esl_event_t *arg1 = (esl_event_t *) 0 ; + int arg2 = (int) 0 ; + void *argp1 = 0 ; + int res1 = 0 ; + int val2 ; + int ecode2 = 0 ; + PyObject * obj0 = 0 ; + PyObject * obj1 = 0 ; + ESLevent *result = 0 ; + + if (!PyArg_ParseTuple(args,(char *)"O|O:new_ESLevent",&obj0,&obj1)) SWIG_fail; + res1 = SWIG_ConvertPtr(obj0, &argp1,SWIGTYPE_p_esl_event_t, 0 | 0 ); + if (!SWIG_IsOK(res1)) { + SWIG_exception_fail(SWIG_ArgError(res1), "in method '" "new_ESLevent" "', argument " "1"" of type '" "esl_event_t *""'"); + } + arg1 = reinterpret_cast< esl_event_t * >(argp1); + if (obj1) { + ecode2 = SWIG_AsVal_int(obj1, &val2); + if (!SWIG_IsOK(ecode2)) { + SWIG_exception_fail(SWIG_ArgError(ecode2), "in method '" "new_ESLevent" "', argument " "2"" of type '" "int""'"); + } + arg2 = static_cast< int >(val2); + } + { + SWIG_PYTHON_THREAD_BEGIN_ALLOW; + result = (ESLevent *)new ESLevent(arg1,arg2); + SWIG_PYTHON_THREAD_END_ALLOW; + } + resultobj = SWIG_NewPointerObj(SWIG_as_voidptr(result), SWIGTYPE_p_ESLevent, SWIG_POINTER_NEW | 0 ); + return resultobj; +fail: + return NULL; +} + + +SWIGINTERN PyObject *_wrap_new_ESLevent__SWIG_2(PyObject *SWIGUNUSEDPARM(self), PyObject *args) { + PyObject *resultobj = 0; + ESLevent *arg1 = (ESLevent *) 0 ; + void *argp1 = 0 ; + int res1 = 0 ; + PyObject * obj0 = 0 ; + ESLevent *result = 0 ; + + if (!PyArg_ParseTuple(args,(char *)"O:new_ESLevent",&obj0)) SWIG_fail; + res1 = SWIG_ConvertPtr(obj0, &argp1,SWIGTYPE_p_ESLevent, 0 | 0 ); + if (!SWIG_IsOK(res1)) { + SWIG_exception_fail(SWIG_ArgError(res1), "in method '" "new_ESLevent" "', argument " "1"" of type '" "ESLevent *""'"); + } + arg1 = reinterpret_cast< ESLevent * >(argp1); + { + SWIG_PYTHON_THREAD_BEGIN_ALLOW; + result = (ESLevent *)new ESLevent(arg1); + SWIG_PYTHON_THREAD_END_ALLOW; + } + resultobj = SWIG_NewPointerObj(SWIG_as_voidptr(result), SWIGTYPE_p_ESLevent, SWIG_POINTER_NEW | 0 ); + return resultobj; +fail: + return NULL; +} + + +SWIGINTERN PyObject *_wrap_new_ESLevent(PyObject *self, PyObject *args) { + int argc; + PyObject *argv[3]; + int ii; + + if (!PyTuple_Check(args)) SWIG_fail; + argc = args ? (int)PyObject_Length(args) : 0; + for (ii = 0; (ii < 2) && (ii < argc); ii++) { + argv[ii] = PyTuple_GET_ITEM(args,ii); + } + if ((argc >= 1) && (argc <= 2)) { + int _v; + void *vptr = 0; + int res = SWIG_ConvertPtr(argv[0], &vptr, SWIGTYPE_p_esl_event_t, 0); + _v = SWIG_CheckState(res); + if (_v) { + if (argc <= 1) { + return _wrap_new_ESLevent__SWIG_1(self, args); + } + { + int res = SWIG_AsVal_int(argv[1], NULL); + _v = SWIG_CheckState(res); + } + if (_v) { + return _wrap_new_ESLevent__SWIG_1(self, args); + } + } + } + if (argc == 1) { + int _v; + void *vptr = 0; + int res = SWIG_ConvertPtr(argv[0], &vptr, SWIGTYPE_p_ESLevent, 0); + _v = SWIG_CheckState(res); + if (_v) { + return _wrap_new_ESLevent__SWIG_2(self, args); + } + } + if ((argc >= 1) && (argc <= 2)) { + int _v; + int res = SWIG_AsCharPtrAndSize(argv[0], 0, NULL, 0); + _v = SWIG_CheckState(res); + if (_v) { + if (argc <= 1) { + return _wrap_new_ESLevent__SWIG_0(self, args); + } + int res = SWIG_AsCharPtrAndSize(argv[1], 0, NULL, 0); + _v = SWIG_CheckState(res); + if (_v) { + return _wrap_new_ESLevent__SWIG_0(self, args); + } + } + } + +fail: + SWIG_SetErrorMsg(PyExc_NotImplementedError,"Wrong number or type of arguments for overloaded function 'new_ESLevent'.\n" + " Possible C/C++ prototypes are:\n" + " ESLevent::ESLevent(char const *,char const *)\n" + " ESLevent::ESLevent(esl_event_t *,int)\n" + " ESLevent::ESLevent(ESLevent *)\n"); + return 0; +} + + +SWIGINTERN PyObject *_wrap_delete_ESLevent(PyObject *SWIGUNUSEDPARM(self), PyObject *args) { + PyObject *resultobj = 0; + ESLevent *arg1 = (ESLevent *) 0 ; + void *argp1 = 0 ; + int res1 = 0 ; + PyObject * obj0 = 0 ; + + if (!PyArg_ParseTuple(args,(char *)"O:delete_ESLevent",&obj0)) SWIG_fail; + res1 = SWIG_ConvertPtr(obj0, &argp1,SWIGTYPE_p_ESLevent, SWIG_POINTER_DISOWN | 0 ); + if (!SWIG_IsOK(res1)) { + SWIG_exception_fail(SWIG_ArgError(res1), "in method '" "delete_ESLevent" "', argument " "1"" of type '" "ESLevent *""'"); + } + arg1 = reinterpret_cast< ESLevent * >(argp1); + { + SWIG_PYTHON_THREAD_BEGIN_ALLOW; + delete arg1; + SWIG_PYTHON_THREAD_END_ALLOW; + } + resultobj = SWIG_Py_Void(); + return resultobj; +fail: + return NULL; +} + + +SWIGINTERN PyObject *_wrap_ESLevent_serialize(PyObject *SWIGUNUSEDPARM(self), PyObject *args) { + PyObject *resultobj = 0; + ESLevent *arg1 = (ESLevent *) 0 ; + char *arg2 = (char *) NULL ; + void *argp1 = 0 ; + int res1 = 0 ; + int res2 ; + char *buf2 = 0 ; + int alloc2 = 0 ; + PyObject * obj0 = 0 ; + PyObject * obj1 = 0 ; + char *result = 0 ; + + if (!PyArg_ParseTuple(args,(char *)"O|O:ESLevent_serialize",&obj0,&obj1)) SWIG_fail; + res1 = SWIG_ConvertPtr(obj0, &argp1,SWIGTYPE_p_ESLevent, 0 | 0 ); + if (!SWIG_IsOK(res1)) { + SWIG_exception_fail(SWIG_ArgError(res1), "in method '" "ESLevent_serialize" "', argument " "1"" of type '" "ESLevent *""'"); + } + arg1 = reinterpret_cast< ESLevent * >(argp1); + if (obj1) { + res2 = SWIG_AsCharPtrAndSize(obj1, &buf2, NULL, &alloc2); + if (!SWIG_IsOK(res2)) { + SWIG_exception_fail(SWIG_ArgError(res2), "in method '" "ESLevent_serialize" "', argument " "2"" of type '" "char const *""'"); + } + arg2 = reinterpret_cast< char * >(buf2); + } + { + SWIG_PYTHON_THREAD_BEGIN_ALLOW; + result = (char *)(arg1)->serialize((char const *)arg2); + SWIG_PYTHON_THREAD_END_ALLOW; + } + resultobj = SWIG_FromCharPtr((const char *)result); + if (alloc2 == SWIG_NEWOBJ) delete[] buf2; + return resultobj; +fail: + if (alloc2 == SWIG_NEWOBJ) delete[] buf2; + return NULL; +} + + +SWIGINTERN PyObject *_wrap_ESLevent_setPriority(PyObject *SWIGUNUSEDPARM(self), PyObject *args) { + PyObject *resultobj = 0; + ESLevent *arg1 = (ESLevent *) 0 ; + esl_priority_t arg2 = (esl_priority_t) ESL_PRIORITY_NORMAL ; + void *argp1 = 0 ; + int res1 = 0 ; + void *argp2 ; + int res2 = 0 ; + PyObject * obj0 = 0 ; + PyObject * obj1 = 0 ; + bool result; + + if (!PyArg_ParseTuple(args,(char *)"O|O:ESLevent_setPriority",&obj0,&obj1)) SWIG_fail; + res1 = SWIG_ConvertPtr(obj0, &argp1,SWIGTYPE_p_ESLevent, 0 | 0 ); + if (!SWIG_IsOK(res1)) { + SWIG_exception_fail(SWIG_ArgError(res1), "in method '" "ESLevent_setPriority" "', argument " "1"" of type '" "ESLevent *""'"); + } + arg1 = reinterpret_cast< ESLevent * >(argp1); + if (obj1) { + { + res2 = SWIG_ConvertPtr(obj1, &argp2, SWIGTYPE_p_esl_priority_t, 0 | 0); + if (!SWIG_IsOK(res2)) { + SWIG_exception_fail(SWIG_ArgError(res2), "in method '" "ESLevent_setPriority" "', argument " "2"" of type '" "esl_priority_t""'"); + } + if (!argp2) { + SWIG_exception_fail(SWIG_ValueError, "invalid null reference " "in method '" "ESLevent_setPriority" "', argument " "2"" of type '" "esl_priority_t""'"); + } else { + esl_priority_t * temp = reinterpret_cast< esl_priority_t * >(argp2); + arg2 = *temp; + if (SWIG_IsNewObj(res2)) delete temp; + } + } + } + { + SWIG_PYTHON_THREAD_BEGIN_ALLOW; + result = (bool)(arg1)->setPriority(arg2); + SWIG_PYTHON_THREAD_END_ALLOW; + } + resultobj = SWIG_From_bool(static_cast< bool >(result)); + return resultobj; +fail: + return NULL; +} + + +SWIGINTERN PyObject *_wrap_ESLevent_getHeader(PyObject *SWIGUNUSEDPARM(self), PyObject *args) { + PyObject *resultobj = 0; + ESLevent *arg1 = (ESLevent *) 0 ; + char *arg2 = (char *) 0 ; + int arg3 = (int) -1 ; + void *argp1 = 0 ; + int res1 = 0 ; + int res2 ; + char *buf2 = 0 ; + int alloc2 = 0 ; + int val3 ; + int ecode3 = 0 ; + PyObject * obj0 = 0 ; + PyObject * obj1 = 0 ; + PyObject * obj2 = 0 ; + char *result = 0 ; + + if (!PyArg_ParseTuple(args,(char *)"OO|O:ESLevent_getHeader",&obj0,&obj1,&obj2)) SWIG_fail; + res1 = SWIG_ConvertPtr(obj0, &argp1,SWIGTYPE_p_ESLevent, 0 | 0 ); + if (!SWIG_IsOK(res1)) { + SWIG_exception_fail(SWIG_ArgError(res1), "in method '" "ESLevent_getHeader" "', argument " "1"" of type '" "ESLevent *""'"); + } + arg1 = reinterpret_cast< ESLevent * >(argp1); + res2 = SWIG_AsCharPtrAndSize(obj1, &buf2, NULL, &alloc2); + if (!SWIG_IsOK(res2)) { + SWIG_exception_fail(SWIG_ArgError(res2), "in method '" "ESLevent_getHeader" "', argument " "2"" of type '" "char const *""'"); + } + arg2 = reinterpret_cast< char * >(buf2); + if (obj2) { + ecode3 = SWIG_AsVal_int(obj2, &val3); + if (!SWIG_IsOK(ecode3)) { + SWIG_exception_fail(SWIG_ArgError(ecode3), "in method '" "ESLevent_getHeader" "', argument " "3"" of type '" "int""'"); + } + arg3 = static_cast< int >(val3); + } + { + SWIG_PYTHON_THREAD_BEGIN_ALLOW; + result = (char *)(arg1)->getHeader((char const *)arg2,arg3); + SWIG_PYTHON_THREAD_END_ALLOW; + } + resultobj = SWIG_FromCharPtr((const char *)result); + if (alloc2 == SWIG_NEWOBJ) delete[] buf2; + return resultobj; +fail: + if (alloc2 == SWIG_NEWOBJ) delete[] buf2; + return NULL; +} + + +SWIGINTERN PyObject *_wrap_ESLevent_getBody(PyObject *SWIGUNUSEDPARM(self), PyObject *args) { + PyObject *resultobj = 0; + ESLevent *arg1 = (ESLevent *) 0 ; + void *argp1 = 0 ; + int res1 = 0 ; + PyObject * obj0 = 0 ; + char *result = 0 ; + + if (!PyArg_ParseTuple(args,(char *)"O:ESLevent_getBody",&obj0)) SWIG_fail; + res1 = SWIG_ConvertPtr(obj0, &argp1,SWIGTYPE_p_ESLevent, 0 | 0 ); + if (!SWIG_IsOK(res1)) { + SWIG_exception_fail(SWIG_ArgError(res1), "in method '" "ESLevent_getBody" "', argument " "1"" of type '" "ESLevent *""'"); + } + arg1 = reinterpret_cast< ESLevent * >(argp1); + { + SWIG_PYTHON_THREAD_BEGIN_ALLOW; + result = (char *)(arg1)->getBody(); + SWIG_PYTHON_THREAD_END_ALLOW; + } + resultobj = SWIG_FromCharPtr((const char *)result); + return resultobj; +fail: + return NULL; +} + + +SWIGINTERN PyObject *_wrap_ESLevent_getType(PyObject *SWIGUNUSEDPARM(self), PyObject *args) { + PyObject *resultobj = 0; + ESLevent *arg1 = (ESLevent *) 0 ; + void *argp1 = 0 ; + int res1 = 0 ; + PyObject * obj0 = 0 ; + char *result = 0 ; + + if (!PyArg_ParseTuple(args,(char *)"O:ESLevent_getType",&obj0)) SWIG_fail; + res1 = SWIG_ConvertPtr(obj0, &argp1,SWIGTYPE_p_ESLevent, 0 | 0 ); + if (!SWIG_IsOK(res1)) { + SWIG_exception_fail(SWIG_ArgError(res1), "in method '" "ESLevent_getType" "', argument " "1"" of type '" "ESLevent *""'"); + } + arg1 = reinterpret_cast< ESLevent * >(argp1); + { + SWIG_PYTHON_THREAD_BEGIN_ALLOW; + result = (char *)(arg1)->getType(); + SWIG_PYTHON_THREAD_END_ALLOW; + } + resultobj = SWIG_FromCharPtr((const char *)result); + return resultobj; +fail: + return NULL; +} + + +SWIGINTERN PyObject *_wrap_ESLevent_addBody(PyObject *SWIGUNUSEDPARM(self), PyObject *args) { + PyObject *resultobj = 0; + ESLevent *arg1 = (ESLevent *) 0 ; + char *arg2 = (char *) 0 ; + void *argp1 = 0 ; + int res1 = 0 ; + int res2 ; + char *buf2 = 0 ; + int alloc2 = 0 ; + PyObject * obj0 = 0 ; + PyObject * obj1 = 0 ; + bool result; + + if (!PyArg_ParseTuple(args,(char *)"OO:ESLevent_addBody",&obj0,&obj1)) SWIG_fail; + res1 = SWIG_ConvertPtr(obj0, &argp1,SWIGTYPE_p_ESLevent, 0 | 0 ); + if (!SWIG_IsOK(res1)) { + SWIG_exception_fail(SWIG_ArgError(res1), "in method '" "ESLevent_addBody" "', argument " "1"" of type '" "ESLevent *""'"); + } + arg1 = reinterpret_cast< ESLevent * >(argp1); + res2 = SWIG_AsCharPtrAndSize(obj1, &buf2, NULL, &alloc2); + if (!SWIG_IsOK(res2)) { + SWIG_exception_fail(SWIG_ArgError(res2), "in method '" "ESLevent_addBody" "', argument " "2"" of type '" "char const *""'"); + } + arg2 = reinterpret_cast< char * >(buf2); + { + SWIG_PYTHON_THREAD_BEGIN_ALLOW; + result = (bool)(arg1)->addBody((char const *)arg2); + SWIG_PYTHON_THREAD_END_ALLOW; + } + resultobj = SWIG_From_bool(static_cast< bool >(result)); + if (alloc2 == SWIG_NEWOBJ) delete[] buf2; + return resultobj; +fail: + if (alloc2 == SWIG_NEWOBJ) delete[] buf2; + return NULL; +} + + +SWIGINTERN PyObject *_wrap_ESLevent_addHeader(PyObject *SWIGUNUSEDPARM(self), PyObject *args) { + PyObject *resultobj = 0; + ESLevent *arg1 = (ESLevent *) 0 ; + char *arg2 = (char *) 0 ; + char *arg3 = (char *) 0 ; + void *argp1 = 0 ; + int res1 = 0 ; + int res2 ; + char *buf2 = 0 ; + int alloc2 = 0 ; + int res3 ; + char *buf3 = 0 ; + int alloc3 = 0 ; + PyObject * obj0 = 0 ; + PyObject * obj1 = 0 ; + PyObject * obj2 = 0 ; + bool result; + + if (!PyArg_ParseTuple(args,(char *)"OOO:ESLevent_addHeader",&obj0,&obj1,&obj2)) SWIG_fail; + res1 = SWIG_ConvertPtr(obj0, &argp1,SWIGTYPE_p_ESLevent, 0 | 0 ); + if (!SWIG_IsOK(res1)) { + SWIG_exception_fail(SWIG_ArgError(res1), "in method '" "ESLevent_addHeader" "', argument " "1"" of type '" "ESLevent *""'"); + } + arg1 = reinterpret_cast< ESLevent * >(argp1); + res2 = SWIG_AsCharPtrAndSize(obj1, &buf2, NULL, &alloc2); + if (!SWIG_IsOK(res2)) { + SWIG_exception_fail(SWIG_ArgError(res2), "in method '" "ESLevent_addHeader" "', argument " "2"" of type '" "char const *""'"); + } + arg2 = reinterpret_cast< char * >(buf2); + res3 = SWIG_AsCharPtrAndSize(obj2, &buf3, NULL, &alloc3); + if (!SWIG_IsOK(res3)) { + SWIG_exception_fail(SWIG_ArgError(res3), "in method '" "ESLevent_addHeader" "', argument " "3"" of type '" "char const *""'"); + } + arg3 = reinterpret_cast< char * >(buf3); + { + SWIG_PYTHON_THREAD_BEGIN_ALLOW; + result = (bool)(arg1)->addHeader((char const *)arg2,(char const *)arg3); + SWIG_PYTHON_THREAD_END_ALLOW; + } + resultobj = SWIG_From_bool(static_cast< bool >(result)); + if (alloc2 == SWIG_NEWOBJ) delete[] buf2; + if (alloc3 == SWIG_NEWOBJ) delete[] buf3; + return resultobj; +fail: + if (alloc2 == SWIG_NEWOBJ) delete[] buf2; + if (alloc3 == SWIG_NEWOBJ) delete[] buf3; + return NULL; +} + + +SWIGINTERN PyObject *_wrap_ESLevent_pushHeader(PyObject *SWIGUNUSEDPARM(self), PyObject *args) { + PyObject *resultobj = 0; + ESLevent *arg1 = (ESLevent *) 0 ; + char *arg2 = (char *) 0 ; + char *arg3 = (char *) 0 ; + void *argp1 = 0 ; + int res1 = 0 ; + int res2 ; + char *buf2 = 0 ; + int alloc2 = 0 ; + int res3 ; + char *buf3 = 0 ; + int alloc3 = 0 ; + PyObject * obj0 = 0 ; + PyObject * obj1 = 0 ; + PyObject * obj2 = 0 ; + bool result; + + if (!PyArg_ParseTuple(args,(char *)"OOO:ESLevent_pushHeader",&obj0,&obj1,&obj2)) SWIG_fail; + res1 = SWIG_ConvertPtr(obj0, &argp1,SWIGTYPE_p_ESLevent, 0 | 0 ); + if (!SWIG_IsOK(res1)) { + SWIG_exception_fail(SWIG_ArgError(res1), "in method '" "ESLevent_pushHeader" "', argument " "1"" of type '" "ESLevent *""'"); + } + arg1 = reinterpret_cast< ESLevent * >(argp1); + res2 = SWIG_AsCharPtrAndSize(obj1, &buf2, NULL, &alloc2); + if (!SWIG_IsOK(res2)) { + SWIG_exception_fail(SWIG_ArgError(res2), "in method '" "ESLevent_pushHeader" "', argument " "2"" of type '" "char const *""'"); + } + arg2 = reinterpret_cast< char * >(buf2); + res3 = SWIG_AsCharPtrAndSize(obj2, &buf3, NULL, &alloc3); + if (!SWIG_IsOK(res3)) { + SWIG_exception_fail(SWIG_ArgError(res3), "in method '" "ESLevent_pushHeader" "', argument " "3"" of type '" "char const *""'"); + } + arg3 = reinterpret_cast< char * >(buf3); + { + SWIG_PYTHON_THREAD_BEGIN_ALLOW; + result = (bool)(arg1)->pushHeader((char const *)arg2,(char const *)arg3); + SWIG_PYTHON_THREAD_END_ALLOW; + } + resultobj = SWIG_From_bool(static_cast< bool >(result)); + if (alloc2 == SWIG_NEWOBJ) delete[] buf2; + if (alloc3 == SWIG_NEWOBJ) delete[] buf3; + return resultobj; +fail: + if (alloc2 == SWIG_NEWOBJ) delete[] buf2; + if (alloc3 == SWIG_NEWOBJ) delete[] buf3; + return NULL; +} + + +SWIGINTERN PyObject *_wrap_ESLevent_unshiftHeader(PyObject *SWIGUNUSEDPARM(self), PyObject *args) { + PyObject *resultobj = 0; + ESLevent *arg1 = (ESLevent *) 0 ; + char *arg2 = (char *) 0 ; + char *arg3 = (char *) 0 ; + void *argp1 = 0 ; + int res1 = 0 ; + int res2 ; + char *buf2 = 0 ; + int alloc2 = 0 ; + int res3 ; + char *buf3 = 0 ; + int alloc3 = 0 ; + PyObject * obj0 = 0 ; + PyObject * obj1 = 0 ; + PyObject * obj2 = 0 ; + bool result; + + if (!PyArg_ParseTuple(args,(char *)"OOO:ESLevent_unshiftHeader",&obj0,&obj1,&obj2)) SWIG_fail; + res1 = SWIG_ConvertPtr(obj0, &argp1,SWIGTYPE_p_ESLevent, 0 | 0 ); + if (!SWIG_IsOK(res1)) { + SWIG_exception_fail(SWIG_ArgError(res1), "in method '" "ESLevent_unshiftHeader" "', argument " "1"" of type '" "ESLevent *""'"); + } + arg1 = reinterpret_cast< ESLevent * >(argp1); + res2 = SWIG_AsCharPtrAndSize(obj1, &buf2, NULL, &alloc2); + if (!SWIG_IsOK(res2)) { + SWIG_exception_fail(SWIG_ArgError(res2), "in method '" "ESLevent_unshiftHeader" "', argument " "2"" of type '" "char const *""'"); + } + arg2 = reinterpret_cast< char * >(buf2); + res3 = SWIG_AsCharPtrAndSize(obj2, &buf3, NULL, &alloc3); + if (!SWIG_IsOK(res3)) { + SWIG_exception_fail(SWIG_ArgError(res3), "in method '" "ESLevent_unshiftHeader" "', argument " "3"" of type '" "char const *""'"); + } + arg3 = reinterpret_cast< char * >(buf3); + { + SWIG_PYTHON_THREAD_BEGIN_ALLOW; + result = (bool)(arg1)->unshiftHeader((char const *)arg2,(char const *)arg3); + SWIG_PYTHON_THREAD_END_ALLOW; + } + resultobj = SWIG_From_bool(static_cast< bool >(result)); + if (alloc2 == SWIG_NEWOBJ) delete[] buf2; + if (alloc3 == SWIG_NEWOBJ) delete[] buf3; + return resultobj; +fail: + if (alloc2 == SWIG_NEWOBJ) delete[] buf2; + if (alloc3 == SWIG_NEWOBJ) delete[] buf3; + return NULL; +} + + +SWIGINTERN PyObject *_wrap_ESLevent_delHeader(PyObject *SWIGUNUSEDPARM(self), PyObject *args) { + PyObject *resultobj = 0; + ESLevent *arg1 = (ESLevent *) 0 ; + char *arg2 = (char *) 0 ; + void *argp1 = 0 ; + int res1 = 0 ; + int res2 ; + char *buf2 = 0 ; + int alloc2 = 0 ; + PyObject * obj0 = 0 ; + PyObject * obj1 = 0 ; + bool result; + + if (!PyArg_ParseTuple(args,(char *)"OO:ESLevent_delHeader",&obj0,&obj1)) SWIG_fail; + res1 = SWIG_ConvertPtr(obj0, &argp1,SWIGTYPE_p_ESLevent, 0 | 0 ); + if (!SWIG_IsOK(res1)) { + SWIG_exception_fail(SWIG_ArgError(res1), "in method '" "ESLevent_delHeader" "', argument " "1"" of type '" "ESLevent *""'"); + } + arg1 = reinterpret_cast< ESLevent * >(argp1); + res2 = SWIG_AsCharPtrAndSize(obj1, &buf2, NULL, &alloc2); + if (!SWIG_IsOK(res2)) { + SWIG_exception_fail(SWIG_ArgError(res2), "in method '" "ESLevent_delHeader" "', argument " "2"" of type '" "char const *""'"); + } + arg2 = reinterpret_cast< char * >(buf2); + { + SWIG_PYTHON_THREAD_BEGIN_ALLOW; + result = (bool)(arg1)->delHeader((char const *)arg2); + SWIG_PYTHON_THREAD_END_ALLOW; + } + resultobj = SWIG_From_bool(static_cast< bool >(result)); + if (alloc2 == SWIG_NEWOBJ) delete[] buf2; + return resultobj; +fail: + if (alloc2 == SWIG_NEWOBJ) delete[] buf2; + return NULL; +} + + +SWIGINTERN PyObject *_wrap_ESLevent_firstHeader(PyObject *SWIGUNUSEDPARM(self), PyObject *args) { + PyObject *resultobj = 0; + ESLevent *arg1 = (ESLevent *) 0 ; + void *argp1 = 0 ; + int res1 = 0 ; + PyObject * obj0 = 0 ; + char *result = 0 ; + + if (!PyArg_ParseTuple(args,(char *)"O:ESLevent_firstHeader",&obj0)) SWIG_fail; + res1 = SWIG_ConvertPtr(obj0, &argp1,SWIGTYPE_p_ESLevent, 0 | 0 ); + if (!SWIG_IsOK(res1)) { + SWIG_exception_fail(SWIG_ArgError(res1), "in method '" "ESLevent_firstHeader" "', argument " "1"" of type '" "ESLevent *""'"); + } + arg1 = reinterpret_cast< ESLevent * >(argp1); + { + SWIG_PYTHON_THREAD_BEGIN_ALLOW; + result = (char *)(arg1)->firstHeader(); + SWIG_PYTHON_THREAD_END_ALLOW; + } + resultobj = SWIG_FromCharPtr((const char *)result); + return resultobj; +fail: + return NULL; +} + + +SWIGINTERN PyObject *_wrap_ESLevent_nextHeader(PyObject *SWIGUNUSEDPARM(self), PyObject *args) { + PyObject *resultobj = 0; + ESLevent *arg1 = (ESLevent *) 0 ; + void *argp1 = 0 ; + int res1 = 0 ; + PyObject * obj0 = 0 ; + char *result = 0 ; + + if (!PyArg_ParseTuple(args,(char *)"O:ESLevent_nextHeader",&obj0)) SWIG_fail; + res1 = SWIG_ConvertPtr(obj0, &argp1,SWIGTYPE_p_ESLevent, 0 | 0 ); + if (!SWIG_IsOK(res1)) { + SWIG_exception_fail(SWIG_ArgError(res1), "in method '" "ESLevent_nextHeader" "', argument " "1"" of type '" "ESLevent *""'"); + } + arg1 = reinterpret_cast< ESLevent * >(argp1); + { + SWIG_PYTHON_THREAD_BEGIN_ALLOW; + result = (char *)(arg1)->nextHeader(); + SWIG_PYTHON_THREAD_END_ALLOW; + } + resultobj = SWIG_FromCharPtr((const char *)result); + return resultobj; +fail: + return NULL; +} + + +SWIGINTERN PyObject *ESLevent_swigregister(PyObject *SWIGUNUSEDPARM(self), PyObject *args) { + PyObject *obj; + if (!PyArg_ParseTuple(args,(char*)"O:swigregister", &obj)) return NULL; + SWIG_TypeNewClientData(SWIGTYPE_p_ESLevent, SWIG_NewClientData(obj)); + return SWIG_Py_Void(); +} + +SWIGINTERN PyObject *_wrap_new_ESLconnection__SWIG_0(PyObject *SWIGUNUSEDPARM(self), PyObject *args) { + PyObject *resultobj = 0; + char *arg1 = (char *) 0 ; + int arg2 ; + char *arg3 = (char *) 0 ; + char *arg4 = (char *) 0 ; + int res1 ; + char *buf1 = 0 ; + int alloc1 = 0 ; + int val2 ; + int ecode2 = 0 ; + int res3 ; + char *buf3 = 0 ; + int alloc3 = 0 ; + int res4 ; + char *buf4 = 0 ; + int alloc4 = 0 ; + PyObject * obj0 = 0 ; + PyObject * obj1 = 0 ; + PyObject * obj2 = 0 ; + PyObject * obj3 = 0 ; + ESLconnection *result = 0 ; + + if (!PyArg_ParseTuple(args,(char *)"OOOO:new_ESLconnection",&obj0,&obj1,&obj2,&obj3)) SWIG_fail; + res1 = SWIG_AsCharPtrAndSize(obj0, &buf1, NULL, &alloc1); + if (!SWIG_IsOK(res1)) { + SWIG_exception_fail(SWIG_ArgError(res1), "in method '" "new_ESLconnection" "', argument " "1"" of type '" "char const *""'"); + } + arg1 = reinterpret_cast< char * >(buf1); + ecode2 = SWIG_AsVal_int(obj1, &val2); + if (!SWIG_IsOK(ecode2)) { + SWIG_exception_fail(SWIG_ArgError(ecode2), "in method '" "new_ESLconnection" "', argument " "2"" of type '" "int""'"); + } + arg2 = static_cast< int >(val2); + res3 = SWIG_AsCharPtrAndSize(obj2, &buf3, NULL, &alloc3); + if (!SWIG_IsOK(res3)) { + SWIG_exception_fail(SWIG_ArgError(res3), "in method '" "new_ESLconnection" "', argument " "3"" of type '" "char const *""'"); + } + arg3 = reinterpret_cast< char * >(buf3); + res4 = SWIG_AsCharPtrAndSize(obj3, &buf4, NULL, &alloc4); + if (!SWIG_IsOK(res4)) { + SWIG_exception_fail(SWIG_ArgError(res4), "in method '" "new_ESLconnection" "', argument " "4"" of type '" "char const *""'"); + } + arg4 = reinterpret_cast< char * >(buf4); + { + SWIG_PYTHON_THREAD_BEGIN_ALLOW; + result = (ESLconnection *)new ESLconnection((char const *)arg1,arg2,(char const *)arg3,(char const *)arg4); + SWIG_PYTHON_THREAD_END_ALLOW; + } + resultobj = SWIG_NewPointerObj(SWIG_as_voidptr(result), SWIGTYPE_p_ESLconnection, SWIG_POINTER_NEW | 0 ); + if (alloc1 == SWIG_NEWOBJ) delete[] buf1; + if (alloc3 == SWIG_NEWOBJ) delete[] buf3; + if (alloc4 == SWIG_NEWOBJ) delete[] buf4; + return resultobj; +fail: + if (alloc1 == SWIG_NEWOBJ) delete[] buf1; + if (alloc3 == SWIG_NEWOBJ) delete[] buf3; + if (alloc4 == SWIG_NEWOBJ) delete[] buf4; + return NULL; +} + + +SWIGINTERN PyObject *_wrap_new_ESLconnection__SWIG_1(PyObject *SWIGUNUSEDPARM(self), PyObject *args) { + PyObject *resultobj = 0; + char *arg1 = (char *) 0 ; + int arg2 ; + char *arg3 = (char *) 0 ; + int res1 ; + char *buf1 = 0 ; + int alloc1 = 0 ; + int val2 ; + int ecode2 = 0 ; + int res3 ; + char *buf3 = 0 ; + int alloc3 = 0 ; + PyObject * obj0 = 0 ; + PyObject * obj1 = 0 ; + PyObject * obj2 = 0 ; + ESLconnection *result = 0 ; + + if (!PyArg_ParseTuple(args,(char *)"OOO:new_ESLconnection",&obj0,&obj1,&obj2)) SWIG_fail; + res1 = SWIG_AsCharPtrAndSize(obj0, &buf1, NULL, &alloc1); + if (!SWIG_IsOK(res1)) { + SWIG_exception_fail(SWIG_ArgError(res1), "in method '" "new_ESLconnection" "', argument " "1"" of type '" "char const *""'"); + } + arg1 = reinterpret_cast< char * >(buf1); + ecode2 = SWIG_AsVal_int(obj1, &val2); + if (!SWIG_IsOK(ecode2)) { + SWIG_exception_fail(SWIG_ArgError(ecode2), "in method '" "new_ESLconnection" "', argument " "2"" of type '" "int""'"); + } + arg2 = static_cast< int >(val2); + res3 = SWIG_AsCharPtrAndSize(obj2, &buf3, NULL, &alloc3); + if (!SWIG_IsOK(res3)) { + SWIG_exception_fail(SWIG_ArgError(res3), "in method '" "new_ESLconnection" "', argument " "3"" of type '" "char const *""'"); + } + arg3 = reinterpret_cast< char * >(buf3); + { + SWIG_PYTHON_THREAD_BEGIN_ALLOW; + result = (ESLconnection *)new ESLconnection((char const *)arg1,arg2,(char const *)arg3); + SWIG_PYTHON_THREAD_END_ALLOW; + } + resultobj = SWIG_NewPointerObj(SWIG_as_voidptr(result), SWIGTYPE_p_ESLconnection, SWIG_POINTER_NEW | 0 ); + if (alloc1 == SWIG_NEWOBJ) delete[] buf1; + if (alloc3 == SWIG_NEWOBJ) delete[] buf3; + return resultobj; +fail: + if (alloc1 == SWIG_NEWOBJ) delete[] buf1; + if (alloc3 == SWIG_NEWOBJ) delete[] buf3; + return NULL; +} + + +SWIGINTERN PyObject *_wrap_new_ESLconnection__SWIG_2(PyObject *SWIGUNUSEDPARM(self), PyObject *args) { + PyObject *resultobj = 0; + char *arg1 = (char *) 0 ; + char *arg2 = (char *) 0 ; + char *arg3 = (char *) 0 ; + char *arg4 = (char *) 0 ; + int res1 ; + char *buf1 = 0 ; + int alloc1 = 0 ; + int res2 ; + char *buf2 = 0 ; + int alloc2 = 0 ; + int res3 ; + char *buf3 = 0 ; + int alloc3 = 0 ; + int res4 ; + char *buf4 = 0 ; + int alloc4 = 0 ; + PyObject * obj0 = 0 ; + PyObject * obj1 = 0 ; + PyObject * obj2 = 0 ; + PyObject * obj3 = 0 ; + ESLconnection *result = 0 ; + + if (!PyArg_ParseTuple(args,(char *)"OOOO:new_ESLconnection",&obj0,&obj1,&obj2,&obj3)) SWIG_fail; + res1 = SWIG_AsCharPtrAndSize(obj0, &buf1, NULL, &alloc1); + if (!SWIG_IsOK(res1)) { + SWIG_exception_fail(SWIG_ArgError(res1), "in method '" "new_ESLconnection" "', argument " "1"" of type '" "char const *""'"); + } + arg1 = reinterpret_cast< char * >(buf1); + res2 = SWIG_AsCharPtrAndSize(obj1, &buf2, NULL, &alloc2); + if (!SWIG_IsOK(res2)) { + SWIG_exception_fail(SWIG_ArgError(res2), "in method '" "new_ESLconnection" "', argument " "2"" of type '" "char const *""'"); + } + arg2 = reinterpret_cast< char * >(buf2); + res3 = SWIG_AsCharPtrAndSize(obj2, &buf3, NULL, &alloc3); + if (!SWIG_IsOK(res3)) { + SWIG_exception_fail(SWIG_ArgError(res3), "in method '" "new_ESLconnection" "', argument " "3"" of type '" "char const *""'"); + } + arg3 = reinterpret_cast< char * >(buf3); + res4 = SWIG_AsCharPtrAndSize(obj3, &buf4, NULL, &alloc4); + if (!SWIG_IsOK(res4)) { + SWIG_exception_fail(SWIG_ArgError(res4), "in method '" "new_ESLconnection" "', argument " "4"" of type '" "char const *""'"); + } + arg4 = reinterpret_cast< char * >(buf4); + { + SWIG_PYTHON_THREAD_BEGIN_ALLOW; + result = (ESLconnection *)new ESLconnection((char const *)arg1,(char const *)arg2,(char const *)arg3,(char const *)arg4); + SWIG_PYTHON_THREAD_END_ALLOW; + } + resultobj = SWIG_NewPointerObj(SWIG_as_voidptr(result), SWIGTYPE_p_ESLconnection, SWIG_POINTER_NEW | 0 ); + if (alloc1 == SWIG_NEWOBJ) delete[] buf1; + if (alloc2 == SWIG_NEWOBJ) delete[] buf2; + if (alloc3 == SWIG_NEWOBJ) delete[] buf3; + if (alloc4 == SWIG_NEWOBJ) delete[] buf4; + return resultobj; +fail: + if (alloc1 == SWIG_NEWOBJ) delete[] buf1; + if (alloc2 == SWIG_NEWOBJ) delete[] buf2; + if (alloc3 == SWIG_NEWOBJ) delete[] buf3; + if (alloc4 == SWIG_NEWOBJ) delete[] buf4; + return NULL; +} + + +SWIGINTERN PyObject *_wrap_new_ESLconnection__SWIG_3(PyObject *SWIGUNUSEDPARM(self), PyObject *args) { + PyObject *resultobj = 0; + char *arg1 = (char *) 0 ; + char *arg2 = (char *) 0 ; + char *arg3 = (char *) 0 ; + int res1 ; + char *buf1 = 0 ; + int alloc1 = 0 ; + int res2 ; + char *buf2 = 0 ; + int alloc2 = 0 ; + int res3 ; + char *buf3 = 0 ; + int alloc3 = 0 ; + PyObject * obj0 = 0 ; + PyObject * obj1 = 0 ; + PyObject * obj2 = 0 ; + ESLconnection *result = 0 ; + + if (!PyArg_ParseTuple(args,(char *)"OOO:new_ESLconnection",&obj0,&obj1,&obj2)) SWIG_fail; + res1 = SWIG_AsCharPtrAndSize(obj0, &buf1, NULL, &alloc1); + if (!SWIG_IsOK(res1)) { + SWIG_exception_fail(SWIG_ArgError(res1), "in method '" "new_ESLconnection" "', argument " "1"" of type '" "char const *""'"); + } + arg1 = reinterpret_cast< char * >(buf1); + res2 = SWIG_AsCharPtrAndSize(obj1, &buf2, NULL, &alloc2); + if (!SWIG_IsOK(res2)) { + SWIG_exception_fail(SWIG_ArgError(res2), "in method '" "new_ESLconnection" "', argument " "2"" of type '" "char const *""'"); + } + arg2 = reinterpret_cast< char * >(buf2); + res3 = SWIG_AsCharPtrAndSize(obj2, &buf3, NULL, &alloc3); + if (!SWIG_IsOK(res3)) { + SWIG_exception_fail(SWIG_ArgError(res3), "in method '" "new_ESLconnection" "', argument " "3"" of type '" "char const *""'"); + } + arg3 = reinterpret_cast< char * >(buf3); + { + SWIG_PYTHON_THREAD_BEGIN_ALLOW; + result = (ESLconnection *)new ESLconnection((char const *)arg1,(char const *)arg2,(char const *)arg3); + SWIG_PYTHON_THREAD_END_ALLOW; + } + resultobj = SWIG_NewPointerObj(SWIG_as_voidptr(result), SWIGTYPE_p_ESLconnection, SWIG_POINTER_NEW | 0 ); + if (alloc1 == SWIG_NEWOBJ) delete[] buf1; + if (alloc2 == SWIG_NEWOBJ) delete[] buf2; + if (alloc3 == SWIG_NEWOBJ) delete[] buf3; + return resultobj; +fail: + if (alloc1 == SWIG_NEWOBJ) delete[] buf1; + if (alloc2 == SWIG_NEWOBJ) delete[] buf2; + if (alloc3 == SWIG_NEWOBJ) delete[] buf3; + return NULL; +} + + +SWIGINTERN PyObject *_wrap_new_ESLconnection__SWIG_4(PyObject *SWIGUNUSEDPARM(self), PyObject *args) { + PyObject *resultobj = 0; + int arg1 ; + int val1 ; + int ecode1 = 0 ; + PyObject * obj0 = 0 ; + ESLconnection *result = 0 ; + + if (!PyArg_ParseTuple(args,(char *)"O:new_ESLconnection",&obj0)) SWIG_fail; + ecode1 = SWIG_AsVal_int(obj0, &val1); + if (!SWIG_IsOK(ecode1)) { + SWIG_exception_fail(SWIG_ArgError(ecode1), "in method '" "new_ESLconnection" "', argument " "1"" of type '" "int""'"); + } + arg1 = static_cast< int >(val1); + { + SWIG_PYTHON_THREAD_BEGIN_ALLOW; + result = (ESLconnection *)new ESLconnection(arg1); + SWIG_PYTHON_THREAD_END_ALLOW; + } + resultobj = SWIG_NewPointerObj(SWIG_as_voidptr(result), SWIGTYPE_p_ESLconnection, SWIG_POINTER_NEW | 0 ); + return resultobj; +fail: + return NULL; +} + + +SWIGINTERN PyObject *_wrap_new_ESLconnection(PyObject *self, PyObject *args) { + int argc; + PyObject *argv[5]; + int ii; + + if (!PyTuple_Check(args)) SWIG_fail; + argc = args ? (int)PyObject_Length(args) : 0; + for (ii = 0; (ii < 4) && (ii < argc); ii++) { + argv[ii] = PyTuple_GET_ITEM(args,ii); + } + if (argc == 1) { + int _v; + { + int res = SWIG_AsVal_int(argv[0], NULL); + _v = SWIG_CheckState(res); + } + if (_v) { + return _wrap_new_ESLconnection__SWIG_4(self, args); + } + } + if (argc == 3) { + int _v; + int res = SWIG_AsCharPtrAndSize(argv[0], 0, NULL, 0); + _v = SWIG_CheckState(res); + if (_v) { + { + int res = SWIG_AsVal_int(argv[1], NULL); + _v = SWIG_CheckState(res); + } + if (_v) { + int res = SWIG_AsCharPtrAndSize(argv[2], 0, NULL, 0); + _v = SWIG_CheckState(res); + if (_v) { + return _wrap_new_ESLconnection__SWIG_1(self, args); + } + } + } + } + if (argc == 3) { + int _v; + int res = SWIG_AsCharPtrAndSize(argv[0], 0, NULL, 0); + _v = SWIG_CheckState(res); + if (_v) { + int res = SWIG_AsCharPtrAndSize(argv[1], 0, NULL, 0); + _v = SWIG_CheckState(res); + if (_v) { + int res = SWIG_AsCharPtrAndSize(argv[2], 0, NULL, 0); + _v = SWIG_CheckState(res); + if (_v) { + return _wrap_new_ESLconnection__SWIG_3(self, args); + } + } + } + } + if (argc == 4) { + int _v; + int res = SWIG_AsCharPtrAndSize(argv[0], 0, NULL, 0); + _v = SWIG_CheckState(res); + if (_v) { + { + int res = SWIG_AsVal_int(argv[1], NULL); + _v = SWIG_CheckState(res); + } + if (_v) { + int res = SWIG_AsCharPtrAndSize(argv[2], 0, NULL, 0); + _v = SWIG_CheckState(res); + if (_v) { + int res = SWIG_AsCharPtrAndSize(argv[3], 0, NULL, 0); + _v = SWIG_CheckState(res); + if (_v) { + return _wrap_new_ESLconnection__SWIG_0(self, args); + } + } + } + } + } + if (argc == 4) { + int _v; + int res = SWIG_AsCharPtrAndSize(argv[0], 0, NULL, 0); + _v = SWIG_CheckState(res); + if (_v) { + int res = SWIG_AsCharPtrAndSize(argv[1], 0, NULL, 0); + _v = SWIG_CheckState(res); + if (_v) { + int res = SWIG_AsCharPtrAndSize(argv[2], 0, NULL, 0); + _v = SWIG_CheckState(res); + if (_v) { + int res = SWIG_AsCharPtrAndSize(argv[3], 0, NULL, 0); + _v = SWIG_CheckState(res); + if (_v) { + return _wrap_new_ESLconnection__SWIG_2(self, args); + } + } + } + } + } + +fail: + SWIG_SetErrorMsg(PyExc_NotImplementedError,"Wrong number or type of arguments for overloaded function 'new_ESLconnection'.\n" + " Possible C/C++ prototypes are:\n" + " ESLconnection::ESLconnection(char const *,int const,char const *,char const *)\n" + " ESLconnection::ESLconnection(char const *,int const,char const *)\n" + " ESLconnection::ESLconnection(char const *,char const *,char const *,char const *)\n" + " ESLconnection::ESLconnection(char const *,char const *,char const *)\n" + " ESLconnection::ESLconnection(int)\n"); + return 0; +} + + +SWIGINTERN PyObject *_wrap_delete_ESLconnection(PyObject *SWIGUNUSEDPARM(self), PyObject *args) { + PyObject *resultobj = 0; + ESLconnection *arg1 = (ESLconnection *) 0 ; + void *argp1 = 0 ; + int res1 = 0 ; + PyObject * obj0 = 0 ; + + if (!PyArg_ParseTuple(args,(char *)"O:delete_ESLconnection",&obj0)) SWIG_fail; + res1 = SWIG_ConvertPtr(obj0, &argp1,SWIGTYPE_p_ESLconnection, SWIG_POINTER_DISOWN | 0 ); + if (!SWIG_IsOK(res1)) { + SWIG_exception_fail(SWIG_ArgError(res1), "in method '" "delete_ESLconnection" "', argument " "1"" of type '" "ESLconnection *""'"); + } + arg1 = reinterpret_cast< ESLconnection * >(argp1); + { + SWIG_PYTHON_THREAD_BEGIN_ALLOW; + delete arg1; + SWIG_PYTHON_THREAD_END_ALLOW; + } + resultobj = SWIG_Py_Void(); + return resultobj; +fail: + return NULL; +} + + +SWIGINTERN PyObject *_wrap_ESLconnection_socketDescriptor(PyObject *SWIGUNUSEDPARM(self), PyObject *args) { + PyObject *resultobj = 0; + ESLconnection *arg1 = (ESLconnection *) 0 ; + void *argp1 = 0 ; + int res1 = 0 ; + PyObject * obj0 = 0 ; + int result; + + if (!PyArg_ParseTuple(args,(char *)"O:ESLconnection_socketDescriptor",&obj0)) SWIG_fail; + res1 = SWIG_ConvertPtr(obj0, &argp1,SWIGTYPE_p_ESLconnection, 0 | 0 ); + if (!SWIG_IsOK(res1)) { + SWIG_exception_fail(SWIG_ArgError(res1), "in method '" "ESLconnection_socketDescriptor" "', argument " "1"" of type '" "ESLconnection *""'"); + } + arg1 = reinterpret_cast< ESLconnection * >(argp1); + { + SWIG_PYTHON_THREAD_BEGIN_ALLOW; + result = (int)(arg1)->socketDescriptor(); + SWIG_PYTHON_THREAD_END_ALLOW; + } + resultobj = SWIG_From_int(static_cast< int >(result)); + return resultobj; +fail: + return NULL; +} + + +SWIGINTERN PyObject *_wrap_ESLconnection_connected(PyObject *SWIGUNUSEDPARM(self), PyObject *args) { + PyObject *resultobj = 0; + ESLconnection *arg1 = (ESLconnection *) 0 ; + void *argp1 = 0 ; + int res1 = 0 ; + PyObject * obj0 = 0 ; + int result; + + if (!PyArg_ParseTuple(args,(char *)"O:ESLconnection_connected",&obj0)) SWIG_fail; + res1 = SWIG_ConvertPtr(obj0, &argp1,SWIGTYPE_p_ESLconnection, 0 | 0 ); + if (!SWIG_IsOK(res1)) { + SWIG_exception_fail(SWIG_ArgError(res1), "in method '" "ESLconnection_connected" "', argument " "1"" of type '" "ESLconnection *""'"); + } + arg1 = reinterpret_cast< ESLconnection * >(argp1); + { + SWIG_PYTHON_THREAD_BEGIN_ALLOW; + result = (int)(arg1)->connected(); + SWIG_PYTHON_THREAD_END_ALLOW; + } + resultobj = SWIG_From_int(static_cast< int >(result)); + return resultobj; +fail: + return NULL; +} + + +SWIGINTERN PyObject *_wrap_ESLconnection_getInfo(PyObject *SWIGUNUSEDPARM(self), PyObject *args) { + PyObject *resultobj = 0; + ESLconnection *arg1 = (ESLconnection *) 0 ; + void *argp1 = 0 ; + int res1 = 0 ; + PyObject * obj0 = 0 ; + ESLevent *result = 0 ; + + if (!PyArg_ParseTuple(args,(char *)"O:ESLconnection_getInfo",&obj0)) SWIG_fail; + res1 = SWIG_ConvertPtr(obj0, &argp1,SWIGTYPE_p_ESLconnection, 0 | 0 ); + if (!SWIG_IsOK(res1)) { + SWIG_exception_fail(SWIG_ArgError(res1), "in method '" "ESLconnection_getInfo" "', argument " "1"" of type '" "ESLconnection *""'"); + } + arg1 = reinterpret_cast< ESLconnection * >(argp1); + { + SWIG_PYTHON_THREAD_BEGIN_ALLOW; + result = (ESLevent *)(arg1)->getInfo(); + SWIG_PYTHON_THREAD_END_ALLOW; + } + resultobj = SWIG_NewPointerObj(SWIG_as_voidptr(result), SWIGTYPE_p_ESLevent, SWIG_POINTER_OWN | 0 ); + return resultobj; +fail: + return NULL; +} + + +SWIGINTERN PyObject *_wrap_ESLconnection_send(PyObject *SWIGUNUSEDPARM(self), PyObject *args) { + PyObject *resultobj = 0; + ESLconnection *arg1 = (ESLconnection *) 0 ; + char *arg2 = (char *) 0 ; + void *argp1 = 0 ; + int res1 = 0 ; + int res2 ; + char *buf2 = 0 ; + int alloc2 = 0 ; + PyObject * obj0 = 0 ; + PyObject * obj1 = 0 ; + int result; + + if (!PyArg_ParseTuple(args,(char *)"OO:ESLconnection_send",&obj0,&obj1)) SWIG_fail; + res1 = SWIG_ConvertPtr(obj0, &argp1,SWIGTYPE_p_ESLconnection, 0 | 0 ); + if (!SWIG_IsOK(res1)) { + SWIG_exception_fail(SWIG_ArgError(res1), "in method '" "ESLconnection_send" "', argument " "1"" of type '" "ESLconnection *""'"); + } + arg1 = reinterpret_cast< ESLconnection * >(argp1); + res2 = SWIG_AsCharPtrAndSize(obj1, &buf2, NULL, &alloc2); + if (!SWIG_IsOK(res2)) { + SWIG_exception_fail(SWIG_ArgError(res2), "in method '" "ESLconnection_send" "', argument " "2"" of type '" "char const *""'"); + } + arg2 = reinterpret_cast< char * >(buf2); + { + SWIG_PYTHON_THREAD_BEGIN_ALLOW; + result = (int)(arg1)->send((char const *)arg2); + SWIG_PYTHON_THREAD_END_ALLOW; + } + resultobj = SWIG_From_int(static_cast< int >(result)); + if (alloc2 == SWIG_NEWOBJ) delete[] buf2; + return resultobj; +fail: + if (alloc2 == SWIG_NEWOBJ) delete[] buf2; + return NULL; +} + + +SWIGINTERN PyObject *_wrap_ESLconnection_sendRecv(PyObject *SWIGUNUSEDPARM(self), PyObject *args) { + PyObject *resultobj = 0; + ESLconnection *arg1 = (ESLconnection *) 0 ; + char *arg2 = (char *) 0 ; + void *argp1 = 0 ; + int res1 = 0 ; + int res2 ; + char *buf2 = 0 ; + int alloc2 = 0 ; + PyObject * obj0 = 0 ; + PyObject * obj1 = 0 ; + ESLevent *result = 0 ; + + if (!PyArg_ParseTuple(args,(char *)"OO:ESLconnection_sendRecv",&obj0,&obj1)) SWIG_fail; + res1 = SWIG_ConvertPtr(obj0, &argp1,SWIGTYPE_p_ESLconnection, 0 | 0 ); + if (!SWIG_IsOK(res1)) { + SWIG_exception_fail(SWIG_ArgError(res1), "in method '" "ESLconnection_sendRecv" "', argument " "1"" of type '" "ESLconnection *""'"); + } + arg1 = reinterpret_cast< ESLconnection * >(argp1); + res2 = SWIG_AsCharPtrAndSize(obj1, &buf2, NULL, &alloc2); + if (!SWIG_IsOK(res2)) { + SWIG_exception_fail(SWIG_ArgError(res2), "in method '" "ESLconnection_sendRecv" "', argument " "2"" of type '" "char const *""'"); + } + arg2 = reinterpret_cast< char * >(buf2); + { + SWIG_PYTHON_THREAD_BEGIN_ALLOW; + result = (ESLevent *)(arg1)->sendRecv((char const *)arg2); + SWIG_PYTHON_THREAD_END_ALLOW; + } + resultobj = SWIG_NewPointerObj(SWIG_as_voidptr(result), SWIGTYPE_p_ESLevent, SWIG_POINTER_OWN | 0 ); + if (alloc2 == SWIG_NEWOBJ) delete[] buf2; + return resultobj; +fail: + if (alloc2 == SWIG_NEWOBJ) delete[] buf2; + return NULL; +} + + +SWIGINTERN PyObject *_wrap_ESLconnection_api(PyObject *SWIGUNUSEDPARM(self), PyObject *args) { + PyObject *resultobj = 0; + ESLconnection *arg1 = (ESLconnection *) 0 ; + char *arg2 = (char *) 0 ; + char *arg3 = (char *) NULL ; + void *argp1 = 0 ; + int res1 = 0 ; + int res2 ; + char *buf2 = 0 ; + int alloc2 = 0 ; + int res3 ; + char *buf3 = 0 ; + int alloc3 = 0 ; + PyObject * obj0 = 0 ; + PyObject * obj1 = 0 ; + PyObject * obj2 = 0 ; + ESLevent *result = 0 ; + + if (!PyArg_ParseTuple(args,(char *)"OO|O:ESLconnection_api",&obj0,&obj1,&obj2)) SWIG_fail; + res1 = SWIG_ConvertPtr(obj0, &argp1,SWIGTYPE_p_ESLconnection, 0 | 0 ); + if (!SWIG_IsOK(res1)) { + SWIG_exception_fail(SWIG_ArgError(res1), "in method '" "ESLconnection_api" "', argument " "1"" of type '" "ESLconnection *""'"); + } + arg1 = reinterpret_cast< ESLconnection * >(argp1); + res2 = SWIG_AsCharPtrAndSize(obj1, &buf2, NULL, &alloc2); + if (!SWIG_IsOK(res2)) { + SWIG_exception_fail(SWIG_ArgError(res2), "in method '" "ESLconnection_api" "', argument " "2"" of type '" "char const *""'"); + } + arg2 = reinterpret_cast< char * >(buf2); + if (obj2) { + res3 = SWIG_AsCharPtrAndSize(obj2, &buf3, NULL, &alloc3); + if (!SWIG_IsOK(res3)) { + SWIG_exception_fail(SWIG_ArgError(res3), "in method '" "ESLconnection_api" "', argument " "3"" of type '" "char const *""'"); + } + arg3 = reinterpret_cast< char * >(buf3); + } + { + SWIG_PYTHON_THREAD_BEGIN_ALLOW; + result = (ESLevent *)(arg1)->api((char const *)arg2,(char const *)arg3); + SWIG_PYTHON_THREAD_END_ALLOW; + } + resultobj = SWIG_NewPointerObj(SWIG_as_voidptr(result), SWIGTYPE_p_ESLevent, SWIG_POINTER_OWN | 0 ); + if (alloc2 == SWIG_NEWOBJ) delete[] buf2; + if (alloc3 == SWIG_NEWOBJ) delete[] buf3; + return resultobj; +fail: + if (alloc2 == SWIG_NEWOBJ) delete[] buf2; + if (alloc3 == SWIG_NEWOBJ) delete[] buf3; + return NULL; +} + + +SWIGINTERN PyObject *_wrap_ESLconnection_bgapi(PyObject *SWIGUNUSEDPARM(self), PyObject *args) { + PyObject *resultobj = 0; + ESLconnection *arg1 = (ESLconnection *) 0 ; + char *arg2 = (char *) 0 ; + char *arg3 = (char *) NULL ; + char *arg4 = (char *) NULL ; + void *argp1 = 0 ; + int res1 = 0 ; + int res2 ; + char *buf2 = 0 ; + int alloc2 = 0 ; + int res3 ; + char *buf3 = 0 ; + int alloc3 = 0 ; + int res4 ; + char *buf4 = 0 ; + int alloc4 = 0 ; + PyObject * obj0 = 0 ; + PyObject * obj1 = 0 ; + PyObject * obj2 = 0 ; + PyObject * obj3 = 0 ; + ESLevent *result = 0 ; + + if (!PyArg_ParseTuple(args,(char *)"OO|OO:ESLconnection_bgapi",&obj0,&obj1,&obj2,&obj3)) SWIG_fail; + res1 = SWIG_ConvertPtr(obj0, &argp1,SWIGTYPE_p_ESLconnection, 0 | 0 ); + if (!SWIG_IsOK(res1)) { + SWIG_exception_fail(SWIG_ArgError(res1), "in method '" "ESLconnection_bgapi" "', argument " "1"" of type '" "ESLconnection *""'"); + } + arg1 = reinterpret_cast< ESLconnection * >(argp1); + res2 = SWIG_AsCharPtrAndSize(obj1, &buf2, NULL, &alloc2); + if (!SWIG_IsOK(res2)) { + SWIG_exception_fail(SWIG_ArgError(res2), "in method '" "ESLconnection_bgapi" "', argument " "2"" of type '" "char const *""'"); + } + arg2 = reinterpret_cast< char * >(buf2); + if (obj2) { + res3 = SWIG_AsCharPtrAndSize(obj2, &buf3, NULL, &alloc3); + if (!SWIG_IsOK(res3)) { + SWIG_exception_fail(SWIG_ArgError(res3), "in method '" "ESLconnection_bgapi" "', argument " "3"" of type '" "char const *""'"); + } + arg3 = reinterpret_cast< char * >(buf3); + } + if (obj3) { + res4 = SWIG_AsCharPtrAndSize(obj3, &buf4, NULL, &alloc4); + if (!SWIG_IsOK(res4)) { + SWIG_exception_fail(SWIG_ArgError(res4), "in method '" "ESLconnection_bgapi" "', argument " "4"" of type '" "char const *""'"); + } + arg4 = reinterpret_cast< char * >(buf4); + } + { + SWIG_PYTHON_THREAD_BEGIN_ALLOW; + result = (ESLevent *)(arg1)->bgapi((char const *)arg2,(char const *)arg3,(char const *)arg4); + SWIG_PYTHON_THREAD_END_ALLOW; + } + resultobj = SWIG_NewPointerObj(SWIG_as_voidptr(result), SWIGTYPE_p_ESLevent, SWIG_POINTER_OWN | 0 ); + if (alloc2 == SWIG_NEWOBJ) delete[] buf2; + if (alloc3 == SWIG_NEWOBJ) delete[] buf3; + if (alloc4 == SWIG_NEWOBJ) delete[] buf4; + return resultobj; +fail: + if (alloc2 == SWIG_NEWOBJ) delete[] buf2; + if (alloc3 == SWIG_NEWOBJ) delete[] buf3; + if (alloc4 == SWIG_NEWOBJ) delete[] buf4; + return NULL; +} + + +SWIGINTERN PyObject *_wrap_ESLconnection_sendEvent(PyObject *SWIGUNUSEDPARM(self), PyObject *args) { + PyObject *resultobj = 0; + ESLconnection *arg1 = (ESLconnection *) 0 ; + ESLevent *arg2 = (ESLevent *) 0 ; + void *argp1 = 0 ; + int res1 = 0 ; + void *argp2 = 0 ; + int res2 = 0 ; + PyObject * obj0 = 0 ; + PyObject * obj1 = 0 ; + ESLevent *result = 0 ; + + if (!PyArg_ParseTuple(args,(char *)"OO:ESLconnection_sendEvent",&obj0,&obj1)) SWIG_fail; + res1 = SWIG_ConvertPtr(obj0, &argp1,SWIGTYPE_p_ESLconnection, 0 | 0 ); + if (!SWIG_IsOK(res1)) { + SWIG_exception_fail(SWIG_ArgError(res1), "in method '" "ESLconnection_sendEvent" "', argument " "1"" of type '" "ESLconnection *""'"); + } + arg1 = reinterpret_cast< ESLconnection * >(argp1); + res2 = SWIG_ConvertPtr(obj1, &argp2,SWIGTYPE_p_ESLevent, 0 | 0 ); + if (!SWIG_IsOK(res2)) { + SWIG_exception_fail(SWIG_ArgError(res2), "in method '" "ESLconnection_sendEvent" "', argument " "2"" of type '" "ESLevent *""'"); + } + arg2 = reinterpret_cast< ESLevent * >(argp2); + { + SWIG_PYTHON_THREAD_BEGIN_ALLOW; + result = (ESLevent *)(arg1)->sendEvent(arg2); + SWIG_PYTHON_THREAD_END_ALLOW; + } + resultobj = SWIG_NewPointerObj(SWIG_as_voidptr(result), SWIGTYPE_p_ESLevent, SWIG_POINTER_OWN | 0 ); + return resultobj; +fail: + return NULL; +} + + +SWIGINTERN PyObject *_wrap_ESLconnection_sendMSG(PyObject *SWIGUNUSEDPARM(self), PyObject *args) { + PyObject *resultobj = 0; + ESLconnection *arg1 = (ESLconnection *) 0 ; + ESLevent *arg2 = (ESLevent *) 0 ; + char *arg3 = (char *) NULL ; + void *argp1 = 0 ; + int res1 = 0 ; + void *argp2 = 0 ; + int res2 = 0 ; + int res3 ; + char *buf3 = 0 ; + int alloc3 = 0 ; + PyObject * obj0 = 0 ; + PyObject * obj1 = 0 ; + PyObject * obj2 = 0 ; + int result; + + if (!PyArg_ParseTuple(args,(char *)"OO|O:ESLconnection_sendMSG",&obj0,&obj1,&obj2)) SWIG_fail; + res1 = SWIG_ConvertPtr(obj0, &argp1,SWIGTYPE_p_ESLconnection, 0 | 0 ); + if (!SWIG_IsOK(res1)) { + SWIG_exception_fail(SWIG_ArgError(res1), "in method '" "ESLconnection_sendMSG" "', argument " "1"" of type '" "ESLconnection *""'"); + } + arg1 = reinterpret_cast< ESLconnection * >(argp1); + res2 = SWIG_ConvertPtr(obj1, &argp2,SWIGTYPE_p_ESLevent, 0 | 0 ); + if (!SWIG_IsOK(res2)) { + SWIG_exception_fail(SWIG_ArgError(res2), "in method '" "ESLconnection_sendMSG" "', argument " "2"" of type '" "ESLevent *""'"); + } + arg2 = reinterpret_cast< ESLevent * >(argp2); + if (obj2) { + res3 = SWIG_AsCharPtrAndSize(obj2, &buf3, NULL, &alloc3); + if (!SWIG_IsOK(res3)) { + SWIG_exception_fail(SWIG_ArgError(res3), "in method '" "ESLconnection_sendMSG" "', argument " "3"" of type '" "char const *""'"); + } + arg3 = reinterpret_cast< char * >(buf3); + } + { + SWIG_PYTHON_THREAD_BEGIN_ALLOW; + result = (int)(arg1)->sendMSG(arg2,(char const *)arg3); + SWIG_PYTHON_THREAD_END_ALLOW; + } + resultobj = SWIG_From_int(static_cast< int >(result)); + if (alloc3 == SWIG_NEWOBJ) delete[] buf3; + return resultobj; +fail: + if (alloc3 == SWIG_NEWOBJ) delete[] buf3; + return NULL; +} + + +SWIGINTERN PyObject *_wrap_ESLconnection_recvEvent(PyObject *SWIGUNUSEDPARM(self), PyObject *args) { + PyObject *resultobj = 0; + ESLconnection *arg1 = (ESLconnection *) 0 ; + void *argp1 = 0 ; + int res1 = 0 ; + PyObject * obj0 = 0 ; + ESLevent *result = 0 ; + + if (!PyArg_ParseTuple(args,(char *)"O:ESLconnection_recvEvent",&obj0)) SWIG_fail; + res1 = SWIG_ConvertPtr(obj0, &argp1,SWIGTYPE_p_ESLconnection, 0 | 0 ); + if (!SWIG_IsOK(res1)) { + SWIG_exception_fail(SWIG_ArgError(res1), "in method '" "ESLconnection_recvEvent" "', argument " "1"" of type '" "ESLconnection *""'"); + } + arg1 = reinterpret_cast< ESLconnection * >(argp1); + { + SWIG_PYTHON_THREAD_BEGIN_ALLOW; + result = (ESLevent *)(arg1)->recvEvent(); + SWIG_PYTHON_THREAD_END_ALLOW; + } + resultobj = SWIG_NewPointerObj(SWIG_as_voidptr(result), SWIGTYPE_p_ESLevent, SWIG_POINTER_OWN | 0 ); + return resultobj; +fail: + return NULL; +} + + +SWIGINTERN PyObject *_wrap_ESLconnection_recvEventTimed(PyObject *SWIGUNUSEDPARM(self), PyObject *args) { + PyObject *resultobj = 0; + ESLconnection *arg1 = (ESLconnection *) 0 ; + int arg2 ; + void *argp1 = 0 ; + int res1 = 0 ; + int val2 ; + int ecode2 = 0 ; + PyObject * obj0 = 0 ; + PyObject * obj1 = 0 ; + ESLevent *result = 0 ; + + if (!PyArg_ParseTuple(args,(char *)"OO:ESLconnection_recvEventTimed",&obj0,&obj1)) SWIG_fail; + res1 = SWIG_ConvertPtr(obj0, &argp1,SWIGTYPE_p_ESLconnection, 0 | 0 ); + if (!SWIG_IsOK(res1)) { + SWIG_exception_fail(SWIG_ArgError(res1), "in method '" "ESLconnection_recvEventTimed" "', argument " "1"" of type '" "ESLconnection *""'"); + } + arg1 = reinterpret_cast< ESLconnection * >(argp1); + ecode2 = SWIG_AsVal_int(obj1, &val2); + if (!SWIG_IsOK(ecode2)) { + SWIG_exception_fail(SWIG_ArgError(ecode2), "in method '" "ESLconnection_recvEventTimed" "', argument " "2"" of type '" "int""'"); + } + arg2 = static_cast< int >(val2); + { + SWIG_PYTHON_THREAD_BEGIN_ALLOW; + result = (ESLevent *)(arg1)->recvEventTimed(arg2); + SWIG_PYTHON_THREAD_END_ALLOW; + } + resultobj = SWIG_NewPointerObj(SWIG_as_voidptr(result), SWIGTYPE_p_ESLevent, SWIG_POINTER_OWN | 0 ); + return resultobj; +fail: + return NULL; +} + + +SWIGINTERN PyObject *_wrap_ESLconnection_filter(PyObject *SWIGUNUSEDPARM(self), PyObject *args) { + PyObject *resultobj = 0; + ESLconnection *arg1 = (ESLconnection *) 0 ; + char *arg2 = (char *) 0 ; + char *arg3 = (char *) 0 ; + void *argp1 = 0 ; + int res1 = 0 ; + int res2 ; + char *buf2 = 0 ; + int alloc2 = 0 ; + int res3 ; + char *buf3 = 0 ; + int alloc3 = 0 ; + PyObject * obj0 = 0 ; + PyObject * obj1 = 0 ; + PyObject * obj2 = 0 ; + ESLevent *result = 0 ; + + if (!PyArg_ParseTuple(args,(char *)"OOO:ESLconnection_filter",&obj0,&obj1,&obj2)) SWIG_fail; + res1 = SWIG_ConvertPtr(obj0, &argp1,SWIGTYPE_p_ESLconnection, 0 | 0 ); + if (!SWIG_IsOK(res1)) { + SWIG_exception_fail(SWIG_ArgError(res1), "in method '" "ESLconnection_filter" "', argument " "1"" of type '" "ESLconnection *""'"); + } + arg1 = reinterpret_cast< ESLconnection * >(argp1); + res2 = SWIG_AsCharPtrAndSize(obj1, &buf2, NULL, &alloc2); + if (!SWIG_IsOK(res2)) { + SWIG_exception_fail(SWIG_ArgError(res2), "in method '" "ESLconnection_filter" "', argument " "2"" of type '" "char const *""'"); + } + arg2 = reinterpret_cast< char * >(buf2); + res3 = SWIG_AsCharPtrAndSize(obj2, &buf3, NULL, &alloc3); + if (!SWIG_IsOK(res3)) { + SWIG_exception_fail(SWIG_ArgError(res3), "in method '" "ESLconnection_filter" "', argument " "3"" of type '" "char const *""'"); + } + arg3 = reinterpret_cast< char * >(buf3); + { + SWIG_PYTHON_THREAD_BEGIN_ALLOW; + result = (ESLevent *)(arg1)->filter((char const *)arg2,(char const *)arg3); + SWIG_PYTHON_THREAD_END_ALLOW; + } + resultobj = SWIG_NewPointerObj(SWIG_as_voidptr(result), SWIGTYPE_p_ESLevent, SWIG_POINTER_OWN | 0 ); + if (alloc2 == SWIG_NEWOBJ) delete[] buf2; + if (alloc3 == SWIG_NEWOBJ) delete[] buf3; + return resultobj; +fail: + if (alloc2 == SWIG_NEWOBJ) delete[] buf2; + if (alloc3 == SWIG_NEWOBJ) delete[] buf3; + return NULL; +} + + +SWIGINTERN PyObject *_wrap_ESLconnection_events(PyObject *SWIGUNUSEDPARM(self), PyObject *args) { + PyObject *resultobj = 0; + ESLconnection *arg1 = (ESLconnection *) 0 ; + char *arg2 = (char *) 0 ; + char *arg3 = (char *) 0 ; + void *argp1 = 0 ; + int res1 = 0 ; + int res2 ; + char *buf2 = 0 ; + int alloc2 = 0 ; + int res3 ; + char *buf3 = 0 ; + int alloc3 = 0 ; + PyObject * obj0 = 0 ; + PyObject * obj1 = 0 ; + PyObject * obj2 = 0 ; + int result; + + if (!PyArg_ParseTuple(args,(char *)"OOO:ESLconnection_events",&obj0,&obj1,&obj2)) SWIG_fail; + res1 = SWIG_ConvertPtr(obj0, &argp1,SWIGTYPE_p_ESLconnection, 0 | 0 ); + if (!SWIG_IsOK(res1)) { + SWIG_exception_fail(SWIG_ArgError(res1), "in method '" "ESLconnection_events" "', argument " "1"" of type '" "ESLconnection *""'"); + } + arg1 = reinterpret_cast< ESLconnection * >(argp1); + res2 = SWIG_AsCharPtrAndSize(obj1, &buf2, NULL, &alloc2); + if (!SWIG_IsOK(res2)) { + SWIG_exception_fail(SWIG_ArgError(res2), "in method '" "ESLconnection_events" "', argument " "2"" of type '" "char const *""'"); + } + arg2 = reinterpret_cast< char * >(buf2); + res3 = SWIG_AsCharPtrAndSize(obj2, &buf3, NULL, &alloc3); + if (!SWIG_IsOK(res3)) { + SWIG_exception_fail(SWIG_ArgError(res3), "in method '" "ESLconnection_events" "', argument " "3"" of type '" "char const *""'"); + } + arg3 = reinterpret_cast< char * >(buf3); + { + SWIG_PYTHON_THREAD_BEGIN_ALLOW; + result = (int)(arg1)->events((char const *)arg2,(char const *)arg3); + SWIG_PYTHON_THREAD_END_ALLOW; + } + resultobj = SWIG_From_int(static_cast< int >(result)); + if (alloc2 == SWIG_NEWOBJ) delete[] buf2; + if (alloc3 == SWIG_NEWOBJ) delete[] buf3; + return resultobj; +fail: + if (alloc2 == SWIG_NEWOBJ) delete[] buf2; + if (alloc3 == SWIG_NEWOBJ) delete[] buf3; + return NULL; +} + + +SWIGINTERN PyObject *_wrap_ESLconnection_execute(PyObject *SWIGUNUSEDPARM(self), PyObject *args) { + PyObject *resultobj = 0; + ESLconnection *arg1 = (ESLconnection *) 0 ; + char *arg2 = (char *) 0 ; + char *arg3 = (char *) NULL ; + char *arg4 = (char *) NULL ; + void *argp1 = 0 ; + int res1 = 0 ; + int res2 ; + char *buf2 = 0 ; + int alloc2 = 0 ; + int res3 ; + char *buf3 = 0 ; + int alloc3 = 0 ; + int res4 ; + char *buf4 = 0 ; + int alloc4 = 0 ; + PyObject * obj0 = 0 ; + PyObject * obj1 = 0 ; + PyObject * obj2 = 0 ; + PyObject * obj3 = 0 ; + ESLevent *result = 0 ; + + if (!PyArg_ParseTuple(args,(char *)"OO|OO:ESLconnection_execute",&obj0,&obj1,&obj2,&obj3)) SWIG_fail; + res1 = SWIG_ConvertPtr(obj0, &argp1,SWIGTYPE_p_ESLconnection, 0 | 0 ); + if (!SWIG_IsOK(res1)) { + SWIG_exception_fail(SWIG_ArgError(res1), "in method '" "ESLconnection_execute" "', argument " "1"" of type '" "ESLconnection *""'"); + } + arg1 = reinterpret_cast< ESLconnection * >(argp1); + res2 = SWIG_AsCharPtrAndSize(obj1, &buf2, NULL, &alloc2); + if (!SWIG_IsOK(res2)) { + SWIG_exception_fail(SWIG_ArgError(res2), "in method '" "ESLconnection_execute" "', argument " "2"" of type '" "char const *""'"); + } + arg2 = reinterpret_cast< char * >(buf2); + if (obj2) { + res3 = SWIG_AsCharPtrAndSize(obj2, &buf3, NULL, &alloc3); + if (!SWIG_IsOK(res3)) { + SWIG_exception_fail(SWIG_ArgError(res3), "in method '" "ESLconnection_execute" "', argument " "3"" of type '" "char const *""'"); + } + arg3 = reinterpret_cast< char * >(buf3); + } + if (obj3) { + res4 = SWIG_AsCharPtrAndSize(obj3, &buf4, NULL, &alloc4); + if (!SWIG_IsOK(res4)) { + SWIG_exception_fail(SWIG_ArgError(res4), "in method '" "ESLconnection_execute" "', argument " "4"" of type '" "char const *""'"); + } + arg4 = reinterpret_cast< char * >(buf4); + } + { + SWIG_PYTHON_THREAD_BEGIN_ALLOW; + result = (ESLevent *)(arg1)->execute((char const *)arg2,(char const *)arg3,(char const *)arg4); + SWIG_PYTHON_THREAD_END_ALLOW; + } + resultobj = SWIG_NewPointerObj(SWIG_as_voidptr(result), SWIGTYPE_p_ESLevent, SWIG_POINTER_OWN | 0 ); + if (alloc2 == SWIG_NEWOBJ) delete[] buf2; + if (alloc3 == SWIG_NEWOBJ) delete[] buf3; + if (alloc4 == SWIG_NEWOBJ) delete[] buf4; + return resultobj; +fail: + if (alloc2 == SWIG_NEWOBJ) delete[] buf2; + if (alloc3 == SWIG_NEWOBJ) delete[] buf3; + if (alloc4 == SWIG_NEWOBJ) delete[] buf4; + return NULL; +} + + +SWIGINTERN PyObject *_wrap_ESLconnection_executeAsync(PyObject *SWIGUNUSEDPARM(self), PyObject *args) { + PyObject *resultobj = 0; + ESLconnection *arg1 = (ESLconnection *) 0 ; + char *arg2 = (char *) 0 ; + char *arg3 = (char *) NULL ; + char *arg4 = (char *) NULL ; + void *argp1 = 0 ; + int res1 = 0 ; + int res2 ; + char *buf2 = 0 ; + int alloc2 = 0 ; + int res3 ; + char *buf3 = 0 ; + int alloc3 = 0 ; + int res4 ; + char *buf4 = 0 ; + int alloc4 = 0 ; + PyObject * obj0 = 0 ; + PyObject * obj1 = 0 ; + PyObject * obj2 = 0 ; + PyObject * obj3 = 0 ; + ESLevent *result = 0 ; + + if (!PyArg_ParseTuple(args,(char *)"OO|OO:ESLconnection_executeAsync",&obj0,&obj1,&obj2,&obj3)) SWIG_fail; + res1 = SWIG_ConvertPtr(obj0, &argp1,SWIGTYPE_p_ESLconnection, 0 | 0 ); + if (!SWIG_IsOK(res1)) { + SWIG_exception_fail(SWIG_ArgError(res1), "in method '" "ESLconnection_executeAsync" "', argument " "1"" of type '" "ESLconnection *""'"); + } + arg1 = reinterpret_cast< ESLconnection * >(argp1); + res2 = SWIG_AsCharPtrAndSize(obj1, &buf2, NULL, &alloc2); + if (!SWIG_IsOK(res2)) { + SWIG_exception_fail(SWIG_ArgError(res2), "in method '" "ESLconnection_executeAsync" "', argument " "2"" of type '" "char const *""'"); + } + arg2 = reinterpret_cast< char * >(buf2); + if (obj2) { + res3 = SWIG_AsCharPtrAndSize(obj2, &buf3, NULL, &alloc3); + if (!SWIG_IsOK(res3)) { + SWIG_exception_fail(SWIG_ArgError(res3), "in method '" "ESLconnection_executeAsync" "', argument " "3"" of type '" "char const *""'"); + } + arg3 = reinterpret_cast< char * >(buf3); + } + if (obj3) { + res4 = SWIG_AsCharPtrAndSize(obj3, &buf4, NULL, &alloc4); + if (!SWIG_IsOK(res4)) { + SWIG_exception_fail(SWIG_ArgError(res4), "in method '" "ESLconnection_executeAsync" "', argument " "4"" of type '" "char const *""'"); + } + arg4 = reinterpret_cast< char * >(buf4); + } + { + SWIG_PYTHON_THREAD_BEGIN_ALLOW; + result = (ESLevent *)(arg1)->executeAsync((char const *)arg2,(char const *)arg3,(char const *)arg4); + SWIG_PYTHON_THREAD_END_ALLOW; + } + resultobj = SWIG_NewPointerObj(SWIG_as_voidptr(result), SWIGTYPE_p_ESLevent, SWIG_POINTER_OWN | 0 ); + if (alloc2 == SWIG_NEWOBJ) delete[] buf2; + if (alloc3 == SWIG_NEWOBJ) delete[] buf3; + if (alloc4 == SWIG_NEWOBJ) delete[] buf4; + return resultobj; +fail: + if (alloc2 == SWIG_NEWOBJ) delete[] buf2; + if (alloc3 == SWIG_NEWOBJ) delete[] buf3; + if (alloc4 == SWIG_NEWOBJ) delete[] buf4; + return NULL; +} + + +SWIGINTERN PyObject *_wrap_ESLconnection_setAsyncExecute(PyObject *SWIGUNUSEDPARM(self), PyObject *args) { + PyObject *resultobj = 0; + ESLconnection *arg1 = (ESLconnection *) 0 ; + char *arg2 = (char *) 0 ; + void *argp1 = 0 ; + int res1 = 0 ; + int res2 ; + char *buf2 = 0 ; + int alloc2 = 0 ; + PyObject * obj0 = 0 ; + PyObject * obj1 = 0 ; + int result; + + if (!PyArg_ParseTuple(args,(char *)"OO:ESLconnection_setAsyncExecute",&obj0,&obj1)) SWIG_fail; + res1 = SWIG_ConvertPtr(obj0, &argp1,SWIGTYPE_p_ESLconnection, 0 | 0 ); + if (!SWIG_IsOK(res1)) { + SWIG_exception_fail(SWIG_ArgError(res1), "in method '" "ESLconnection_setAsyncExecute" "', argument " "1"" of type '" "ESLconnection *""'"); + } + arg1 = reinterpret_cast< ESLconnection * >(argp1); + res2 = SWIG_AsCharPtrAndSize(obj1, &buf2, NULL, &alloc2); + if (!SWIG_IsOK(res2)) { + SWIG_exception_fail(SWIG_ArgError(res2), "in method '" "ESLconnection_setAsyncExecute" "', argument " "2"" of type '" "char const *""'"); + } + arg2 = reinterpret_cast< char * >(buf2); + { + SWIG_PYTHON_THREAD_BEGIN_ALLOW; + result = (int)(arg1)->setAsyncExecute((char const *)arg2); + SWIG_PYTHON_THREAD_END_ALLOW; + } + resultobj = SWIG_From_int(static_cast< int >(result)); + if (alloc2 == SWIG_NEWOBJ) delete[] buf2; + return resultobj; +fail: + if (alloc2 == SWIG_NEWOBJ) delete[] buf2; + return NULL; +} + + +SWIGINTERN PyObject *_wrap_ESLconnection_setEventLock(PyObject *SWIGUNUSEDPARM(self), PyObject *args) { + PyObject *resultobj = 0; + ESLconnection *arg1 = (ESLconnection *) 0 ; + char *arg2 = (char *) 0 ; + void *argp1 = 0 ; + int res1 = 0 ; + int res2 ; + char *buf2 = 0 ; + int alloc2 = 0 ; + PyObject * obj0 = 0 ; + PyObject * obj1 = 0 ; + int result; + + if (!PyArg_ParseTuple(args,(char *)"OO:ESLconnection_setEventLock",&obj0,&obj1)) SWIG_fail; + res1 = SWIG_ConvertPtr(obj0, &argp1,SWIGTYPE_p_ESLconnection, 0 | 0 ); + if (!SWIG_IsOK(res1)) { + SWIG_exception_fail(SWIG_ArgError(res1), "in method '" "ESLconnection_setEventLock" "', argument " "1"" of type '" "ESLconnection *""'"); + } + arg1 = reinterpret_cast< ESLconnection * >(argp1); + res2 = SWIG_AsCharPtrAndSize(obj1, &buf2, NULL, &alloc2); + if (!SWIG_IsOK(res2)) { + SWIG_exception_fail(SWIG_ArgError(res2), "in method '" "ESLconnection_setEventLock" "', argument " "2"" of type '" "char const *""'"); + } + arg2 = reinterpret_cast< char * >(buf2); + { + SWIG_PYTHON_THREAD_BEGIN_ALLOW; + result = (int)(arg1)->setEventLock((char const *)arg2); + SWIG_PYTHON_THREAD_END_ALLOW; + } + resultobj = SWIG_From_int(static_cast< int >(result)); + if (alloc2 == SWIG_NEWOBJ) delete[] buf2; + return resultobj; +fail: + if (alloc2 == SWIG_NEWOBJ) delete[] buf2; + return NULL; +} + + +SWIGINTERN PyObject *_wrap_ESLconnection_disconnect(PyObject *SWIGUNUSEDPARM(self), PyObject *args) { + PyObject *resultobj = 0; + ESLconnection *arg1 = (ESLconnection *) 0 ; + void *argp1 = 0 ; + int res1 = 0 ; + PyObject * obj0 = 0 ; + int result; + + if (!PyArg_ParseTuple(args,(char *)"O:ESLconnection_disconnect",&obj0)) SWIG_fail; + res1 = SWIG_ConvertPtr(obj0, &argp1,SWIGTYPE_p_ESLconnection, 0 | 0 ); + if (!SWIG_IsOK(res1)) { + SWIG_exception_fail(SWIG_ArgError(res1), "in method '" "ESLconnection_disconnect" "', argument " "1"" of type '" "ESLconnection *""'"); + } + arg1 = reinterpret_cast< ESLconnection * >(argp1); + { + SWIG_PYTHON_THREAD_BEGIN_ALLOW; + result = (int)(arg1)->disconnect(); + SWIG_PYTHON_THREAD_END_ALLOW; + } + resultobj = SWIG_From_int(static_cast< int >(result)); + return resultobj; +fail: + return NULL; +} + + +SWIGINTERN PyObject *ESLconnection_swigregister(PyObject *SWIGUNUSEDPARM(self), PyObject *args) { + PyObject *obj; + if (!PyArg_ParseTuple(args,(char*)"O:swigregister", &obj)) return NULL; + SWIG_TypeNewClientData(SWIGTYPE_p_ESLconnection, SWIG_NewClientData(obj)); + return SWIG_Py_Void(); +} + +SWIGINTERN PyObject *_wrap_eslSetLogLevel(PyObject *SWIGUNUSEDPARM(self), PyObject *args) { + PyObject *resultobj = 0; + int arg1 ; + int val1 ; + int ecode1 = 0 ; + PyObject * obj0 = 0 ; + + if (!PyArg_ParseTuple(args,(char *)"O:eslSetLogLevel",&obj0)) SWIG_fail; + ecode1 = SWIG_AsVal_int(obj0, &val1); + if (!SWIG_IsOK(ecode1)) { + SWIG_exception_fail(SWIG_ArgError(ecode1), "in method '" "eslSetLogLevel" "', argument " "1"" of type '" "int""'"); + } + arg1 = static_cast< int >(val1); + { + SWIG_PYTHON_THREAD_BEGIN_ALLOW; + eslSetLogLevel(arg1); + SWIG_PYTHON_THREAD_END_ALLOW; + } + resultobj = SWIG_Py_Void(); + return resultobj; +fail: + return NULL; +} + + +static PyMethodDef SwigMethods[] = { + { (char *)"SWIG_PyInstanceMethod_New", (PyCFunction)SWIG_PyInstanceMethod_New, METH_O, NULL}, + { (char *)"ESLevent_event_set", _wrap_ESLevent_event_set, METH_VARARGS, NULL}, + { (char *)"ESLevent_event_get", _wrap_ESLevent_event_get, METH_VARARGS, NULL}, + { (char *)"ESLevent_serialized_string_set", _wrap_ESLevent_serialized_string_set, METH_VARARGS, NULL}, + { (char *)"ESLevent_serialized_string_get", _wrap_ESLevent_serialized_string_get, METH_VARARGS, NULL}, + { (char *)"ESLevent_mine_set", _wrap_ESLevent_mine_set, METH_VARARGS, NULL}, + { (char *)"ESLevent_mine_get", _wrap_ESLevent_mine_get, METH_VARARGS, NULL}, + { (char *)"new_ESLevent", _wrap_new_ESLevent, METH_VARARGS, NULL}, + { (char *)"delete_ESLevent", _wrap_delete_ESLevent, METH_VARARGS, NULL}, + { (char *)"ESLevent_serialize", _wrap_ESLevent_serialize, METH_VARARGS, NULL}, + { (char *)"ESLevent_setPriority", _wrap_ESLevent_setPriority, METH_VARARGS, NULL}, + { (char *)"ESLevent_getHeader", _wrap_ESLevent_getHeader, METH_VARARGS, NULL}, + { (char *)"ESLevent_getBody", _wrap_ESLevent_getBody, METH_VARARGS, NULL}, + { (char *)"ESLevent_getType", _wrap_ESLevent_getType, METH_VARARGS, NULL}, + { (char *)"ESLevent_addBody", _wrap_ESLevent_addBody, METH_VARARGS, NULL}, + { (char *)"ESLevent_addHeader", _wrap_ESLevent_addHeader, METH_VARARGS, NULL}, + { (char *)"ESLevent_pushHeader", _wrap_ESLevent_pushHeader, METH_VARARGS, NULL}, + { (char *)"ESLevent_unshiftHeader", _wrap_ESLevent_unshiftHeader, METH_VARARGS, NULL}, + { (char *)"ESLevent_delHeader", _wrap_ESLevent_delHeader, METH_VARARGS, NULL}, + { (char *)"ESLevent_firstHeader", _wrap_ESLevent_firstHeader, METH_VARARGS, NULL}, + { (char *)"ESLevent_nextHeader", _wrap_ESLevent_nextHeader, METH_VARARGS, NULL}, + { (char *)"ESLevent_swigregister", ESLevent_swigregister, METH_VARARGS, NULL}, + { (char *)"new_ESLconnection", _wrap_new_ESLconnection, METH_VARARGS, NULL}, + { (char *)"delete_ESLconnection", _wrap_delete_ESLconnection, METH_VARARGS, NULL}, + { (char *)"ESLconnection_socketDescriptor", _wrap_ESLconnection_socketDescriptor, METH_VARARGS, NULL}, + { (char *)"ESLconnection_connected", _wrap_ESLconnection_connected, METH_VARARGS, NULL}, + { (char *)"ESLconnection_getInfo", _wrap_ESLconnection_getInfo, METH_VARARGS, NULL}, + { (char *)"ESLconnection_send", _wrap_ESLconnection_send, METH_VARARGS, NULL}, + { (char *)"ESLconnection_sendRecv", _wrap_ESLconnection_sendRecv, METH_VARARGS, NULL}, + { (char *)"ESLconnection_api", _wrap_ESLconnection_api, METH_VARARGS, NULL}, + { (char *)"ESLconnection_bgapi", _wrap_ESLconnection_bgapi, METH_VARARGS, NULL}, + { (char *)"ESLconnection_sendEvent", _wrap_ESLconnection_sendEvent, METH_VARARGS, NULL}, + { (char *)"ESLconnection_sendMSG", _wrap_ESLconnection_sendMSG, METH_VARARGS, NULL}, + { (char *)"ESLconnection_recvEvent", _wrap_ESLconnection_recvEvent, METH_VARARGS, NULL}, + { (char *)"ESLconnection_recvEventTimed", _wrap_ESLconnection_recvEventTimed, METH_VARARGS, NULL}, + { (char *)"ESLconnection_filter", _wrap_ESLconnection_filter, METH_VARARGS, NULL}, + { (char *)"ESLconnection_events", _wrap_ESLconnection_events, METH_VARARGS, NULL}, + { (char *)"ESLconnection_execute", _wrap_ESLconnection_execute, METH_VARARGS, NULL}, + { (char *)"ESLconnection_executeAsync", _wrap_ESLconnection_executeAsync, METH_VARARGS, NULL}, + { (char *)"ESLconnection_setAsyncExecute", _wrap_ESLconnection_setAsyncExecute, METH_VARARGS, NULL}, + { (char *)"ESLconnection_setEventLock", _wrap_ESLconnection_setEventLock, METH_VARARGS, NULL}, + { (char *)"ESLconnection_disconnect", _wrap_ESLconnection_disconnect, METH_VARARGS, NULL}, + { (char *)"ESLconnection_swigregister", ESLconnection_swigregister, METH_VARARGS, NULL}, + { (char *)"eslSetLogLevel", _wrap_eslSetLogLevel, METH_VARARGS, NULL}, + { NULL, NULL, 0, NULL } +}; + + +/* -------- TYPE CONVERSION AND EQUIVALENCE RULES (BEGIN) -------- */ + +static swig_type_info _swigt__p_ESLconnection = {"_p_ESLconnection", "ESLconnection *", 0, 0, (void*)0, 0}; +static swig_type_info _swigt__p_ESLevent = {"_p_ESLevent", "ESLevent *", 0, 0, (void*)0, 0}; +static swig_type_info _swigt__p_char = {"_p_char", "char *", 0, 0, (void*)0, 0}; +static swig_type_info _swigt__p_esl_event_t = {"_p_esl_event_t", "esl_event_t *", 0, 0, (void*)0, 0}; +static swig_type_info _swigt__p_esl_priority_t = {"_p_esl_priority_t", "esl_priority_t *", 0, 0, (void*)0, 0}; + +static swig_type_info *swig_type_initial[] = { + &_swigt__p_ESLconnection, + &_swigt__p_ESLevent, + &_swigt__p_char, + &_swigt__p_esl_event_t, + &_swigt__p_esl_priority_t, +}; + +static swig_cast_info _swigc__p_ESLconnection[] = { {&_swigt__p_ESLconnection, 0, 0, 0},{0, 0, 0, 0}}; +static swig_cast_info _swigc__p_ESLevent[] = { {&_swigt__p_ESLevent, 0, 0, 0},{0, 0, 0, 0}}; +static swig_cast_info _swigc__p_char[] = { {&_swigt__p_char, 0, 0, 0},{0, 0, 0, 0}}; +static swig_cast_info _swigc__p_esl_event_t[] = { {&_swigt__p_esl_event_t, 0, 0, 0},{0, 0, 0, 0}}; +static swig_cast_info _swigc__p_esl_priority_t[] = { {&_swigt__p_esl_priority_t, 0, 0, 0},{0, 0, 0, 0}}; + +static swig_cast_info *swig_cast_initial[] = { + _swigc__p_ESLconnection, + _swigc__p_ESLevent, + _swigc__p_char, + _swigc__p_esl_event_t, + _swigc__p_esl_priority_t, +}; + + +/* -------- TYPE CONVERSION AND EQUIVALENCE RULES (END) -------- */ + +static swig_const_info swig_const_table[] = { +{0, 0, 0, 0.0, 0, 0}}; + +#ifdef __cplusplus +} +#endif +/* ----------------------------------------------------------------------------- + * Type initialization: + * This problem is tough by the requirement that no dynamic + * memory is used. Also, since swig_type_info structures store pointers to + * swig_cast_info structures and swig_cast_info structures store pointers back + * to swig_type_info structures, we need some lookup code at initialization. + * The idea is that swig generates all the structures that are needed. + * The runtime then collects these partially filled structures. + * The SWIG_InitializeModule function takes these initial arrays out of + * swig_module, and does all the lookup, filling in the swig_module.types + * array with the correct data and linking the correct swig_cast_info + * structures together. + * + * The generated swig_type_info structures are assigned statically to an initial + * array. We just loop through that array, and handle each type individually. + * First we lookup if this type has been already loaded, and if so, use the + * loaded structure instead of the generated one. Then we have to fill in the + * cast linked list. The cast data is initially stored in something like a + * two-dimensional array. Each row corresponds to a type (there are the same + * number of rows as there are in the swig_type_initial array). Each entry in + * a column is one of the swig_cast_info structures for that type. + * The cast_initial array is actually an array of arrays, because each row has + * a variable number of columns. So to actually build the cast linked list, + * we find the array of casts associated with the type, and loop through it + * adding the casts to the list. The one last trick we need to do is making + * sure the type pointer in the swig_cast_info struct is correct. + * + * First off, we lookup the cast->type name to see if it is already loaded. + * There are three cases to handle: + * 1) If the cast->type has already been loaded AND the type we are adding + * casting info to has not been loaded (it is in this module), THEN we + * replace the cast->type pointer with the type pointer that has already + * been loaded. + * 2) If BOTH types (the one we are adding casting info to, and the + * cast->type) are loaded, THEN the cast info has already been loaded by + * the previous module so we just ignore it. + * 3) Finally, if cast->type has not already been loaded, then we add that + * swig_cast_info to the linked list (because the cast->type) pointer will + * be correct. + * ----------------------------------------------------------------------------- */ + +#ifdef __cplusplus +extern "C" { +#if 0 +} /* c-mode */ +#endif +#endif + +#if 0 +#define SWIGRUNTIME_DEBUG +#endif + + +SWIGRUNTIME void +SWIG_InitializeModule(void *clientdata) { + size_t i; + swig_module_info *module_head, *iter; + int found, init; + + /* check to see if the circular list has been setup, if not, set it up */ + if (swig_module.next==0) { + /* Initialize the swig_module */ + swig_module.type_initial = swig_type_initial; + swig_module.cast_initial = swig_cast_initial; + swig_module.next = &swig_module; + init = 1; + } else { + init = 0; + } + + /* Try and load any already created modules */ + module_head = SWIG_GetModule(clientdata); + if (!module_head) { + /* This is the first module loaded for this interpreter */ + /* so set the swig module into the interpreter */ + SWIG_SetModule(clientdata, &swig_module); + module_head = &swig_module; + } else { + /* the interpreter has loaded a SWIG module, but has it loaded this one? */ + found=0; + iter=module_head; + do { + if (iter==&swig_module) { + found=1; + break; + } + iter=iter->next; + } while (iter!= module_head); + + /* if the is found in the list, then all is done and we may leave */ + if (found) return; + /* otherwise we must add out module into the list */ + swig_module.next = module_head->next; + module_head->next = &swig_module; + } + + /* When multiple interpreters are used, a module could have already been initialized in + a different interpreter, but not yet have a pointer in this interpreter. + In this case, we do not want to continue adding types... everything should be + set up already */ + if (init == 0) return; + + /* Now work on filling in swig_module.types */ +#ifdef SWIGRUNTIME_DEBUG + printf("SWIG_InitializeModule: size %d\n", swig_module.size); +#endif + for (i = 0; i < swig_module.size; ++i) { + swig_type_info *type = 0; + swig_type_info *ret; + swig_cast_info *cast; + +#ifdef SWIGRUNTIME_DEBUG + printf("SWIG_InitializeModule: type %d %s\n", i, swig_module.type_initial[i]->name); +#endif + + /* if there is another module already loaded */ + if (swig_module.next != &swig_module) { + type = SWIG_MangledTypeQueryModule(swig_module.next, &swig_module, swig_module.type_initial[i]->name); + } + if (type) { + /* Overwrite clientdata field */ +#ifdef SWIGRUNTIME_DEBUG + printf("SWIG_InitializeModule: found type %s\n", type->name); +#endif + if (swig_module.type_initial[i]->clientdata) { + type->clientdata = swig_module.type_initial[i]->clientdata; +#ifdef SWIGRUNTIME_DEBUG + printf("SWIG_InitializeModule: found and overwrite type %s \n", type->name); +#endif + } + } else { + type = swig_module.type_initial[i]; + } + + /* Insert casting types */ + cast = swig_module.cast_initial[i]; + while (cast->type) { + /* Don't need to add information already in the list */ + ret = 0; +#ifdef SWIGRUNTIME_DEBUG + printf("SWIG_InitializeModule: look cast %s\n", cast->type->name); +#endif + if (swig_module.next != &swig_module) { + ret = SWIG_MangledTypeQueryModule(swig_module.next, &swig_module, cast->type->name); +#ifdef SWIGRUNTIME_DEBUG + if (ret) printf("SWIG_InitializeModule: found cast %s\n", ret->name); +#endif + } + if (ret) { + if (type == swig_module.type_initial[i]) { +#ifdef SWIGRUNTIME_DEBUG + printf("SWIG_InitializeModule: skip old type %s\n", ret->name); +#endif + cast->type = ret; + ret = 0; + } else { + /* Check for casting already in the list */ + swig_cast_info *ocast = SWIG_TypeCheck(ret->name, type); +#ifdef SWIGRUNTIME_DEBUG + if (ocast) printf("SWIG_InitializeModule: skip old cast %s\n", ret->name); +#endif + if (!ocast) ret = 0; + } + } + + if (!ret) { +#ifdef SWIGRUNTIME_DEBUG + printf("SWIG_InitializeModule: adding cast %s\n", cast->type->name); +#endif + if (type->cast) { + type->cast->prev = cast; + cast->next = type->cast; + } + type->cast = cast; + } + cast++; + } + /* Set entry in modules->types array equal to the type */ + swig_module.types[i] = type; + } + swig_module.types[i] = 0; + +#ifdef SWIGRUNTIME_DEBUG + printf("**** SWIG_InitializeModule: Cast List ******\n"); + for (i = 0; i < swig_module.size; ++i) { + int j = 0; + swig_cast_info *cast = swig_module.cast_initial[i]; + printf("SWIG_InitializeModule: type %d %s\n", i, swig_module.type_initial[i]->name); + while (cast->type) { + printf("SWIG_InitializeModule: cast type %s\n", cast->type->name); + cast++; + ++j; + } + printf("---- Total casts: %d\n",j); + } + printf("**** SWIG_InitializeModule: Cast List ******\n"); +#endif +} + +/* This function will propagate the clientdata field of type to +* any new swig_type_info structures that have been added into the list +* of equivalent types. It is like calling +* SWIG_TypeClientData(type, clientdata) a second time. +*/ +SWIGRUNTIME void +SWIG_PropagateClientData(void) { + size_t i; + swig_cast_info *equiv; + static int init_run = 0; + + if (init_run) return; + init_run = 1; + + for (i = 0; i < swig_module.size; i++) { + if (swig_module.types[i]->clientdata) { + equiv = swig_module.types[i]->cast; + while (equiv) { + if (!equiv->converter) { + if (equiv->type && !equiv->type->clientdata) + SWIG_TypeClientData(equiv->type, swig_module.types[i]->clientdata); + } + equiv = equiv->next; + } + } + } +} + +#ifdef __cplusplus +#if 0 +{ + /* c-mode */ +#endif +} +#endif + + + +#ifdef __cplusplus +extern "C" { +#endif + + /* Python-specific SWIG API */ +#define SWIG_newvarlink() SWIG_Python_newvarlink() +#define SWIG_addvarlink(p, name, get_attr, set_attr) SWIG_Python_addvarlink(p, name, get_attr, set_attr) +#define SWIG_InstallConstants(d, constants) SWIG_Python_InstallConstants(d, constants) + + /* ----------------------------------------------------------------------------- + * global variable support code. + * ----------------------------------------------------------------------------- */ + + typedef struct swig_globalvar { + char *name; /* Name of global variable */ + PyObject *(*get_attr)(void); /* Return the current value */ + int (*set_attr)(PyObject *); /* Set the value */ + struct swig_globalvar *next; + } swig_globalvar; + + typedef struct swig_varlinkobject { + PyObject_HEAD + swig_globalvar *vars; + } swig_varlinkobject; + + SWIGINTERN PyObject * + swig_varlink_repr(swig_varlinkobject *SWIGUNUSEDPARM(v)) { +#if PY_VERSION_HEX >= 0x03000000 + return PyUnicode_InternFromString(""); +#else + return PyString_FromString(""); +#endif + } + + SWIGINTERN PyObject * + swig_varlink_str(swig_varlinkobject *v) { +#if PY_VERSION_HEX >= 0x03000000 + PyObject *str = PyUnicode_InternFromString("("); + PyObject *tail; + PyObject *joined; + swig_globalvar *var; + for (var = v->vars; var; var=var->next) { + tail = PyUnicode_FromString(var->name); + joined = PyUnicode_Concat(str, tail); + Py_DecRef(str); + Py_DecRef(tail); + str = joined; + if (var->next) { + tail = PyUnicode_InternFromString(", "); + joined = PyUnicode_Concat(str, tail); + Py_DecRef(str); + Py_DecRef(tail); + str = joined; + } + } + tail = PyUnicode_InternFromString(")"); + joined = PyUnicode_Concat(str, tail); + Py_DecRef(str); + Py_DecRef(tail); + str = joined; +#else + PyObject *str = PyString_FromString("("); + swig_globalvar *var; + for (var = v->vars; var; var=var->next) { + PyString_ConcatAndDel(&str,PyString_FromString(var->name)); + if (var->next) PyString_ConcatAndDel(&str,PyString_FromString(", ")); + } + PyString_ConcatAndDel(&str,PyString_FromString(")")); +#endif + return str; + } + + SWIGINTERN int + swig_varlink_print(swig_varlinkobject *v, FILE *fp, int SWIGUNUSEDPARM(flags)) { + char *tmp; + PyObject *str = swig_varlink_str(v); + fprintf(fp,"Swig global variables "); + fprintf(fp,"%s\n", tmp = SWIG_Python_str_AsChar(str)); + SWIG_Python_str_DelForPy3(tmp); + Py_DECREF(str); + return 0; + } + + SWIGINTERN void + swig_varlink_dealloc(swig_varlinkobject *v) { + swig_globalvar *var = v->vars; + while (var) { + swig_globalvar *n = var->next; + free(var->name); + free(var); + var = n; + } + } + + SWIGINTERN PyObject * + swig_varlink_getattr(swig_varlinkobject *v, char *n) { + PyObject *res = NULL; + swig_globalvar *var = v->vars; + while (var) { + if (strcmp(var->name,n) == 0) { + res = (*var->get_attr)(); + break; + } + var = var->next; + } + if (res == NULL && !PyErr_Occurred()) { + PyErr_Format(PyExc_AttributeError, "Unknown C global variable '%s'", n); + } + return res; + } + + SWIGINTERN int + swig_varlink_setattr(swig_varlinkobject *v, char *n, PyObject *p) { + int res = 1; + swig_globalvar *var = v->vars; + while (var) { + if (strcmp(var->name,n) == 0) { + res = (*var->set_attr)(p); + break; + } + var = var->next; + } + if (res == 1 && !PyErr_Occurred()) { + PyErr_Format(PyExc_AttributeError, "Unknown C global variable '%s'", n); + } + return res; + } + + SWIGINTERN PyTypeObject* + swig_varlink_type(void) { + static char varlink__doc__[] = "Swig var link object"; + static PyTypeObject varlink_type; + static int type_init = 0; + if (!type_init) { + const PyTypeObject tmp = { + /* PyObject header changed in Python 3 */ +#if PY_VERSION_HEX >= 0x03000000 + PyVarObject_HEAD_INIT(NULL, 0) +#else + PyObject_HEAD_INIT(NULL) + 0, /* ob_size */ +#endif + (char *)"swigvarlink", /* tp_name */ + sizeof(swig_varlinkobject), /* tp_basicsize */ + 0, /* tp_itemsize */ + (destructor) swig_varlink_dealloc, /* tp_dealloc */ + (printfunc) swig_varlink_print, /* tp_print */ + (getattrfunc) swig_varlink_getattr, /* tp_getattr */ + (setattrfunc) swig_varlink_setattr, /* tp_setattr */ + 0, /* tp_compare */ + (reprfunc) swig_varlink_repr, /* tp_repr */ + 0, /* tp_as_number */ + 0, /* tp_as_sequence */ + 0, /* tp_as_mapping */ + 0, /* tp_hash */ + 0, /* tp_call */ + (reprfunc) swig_varlink_str, /* tp_str */ + 0, /* tp_getattro */ + 0, /* tp_setattro */ + 0, /* tp_as_buffer */ + 0, /* tp_flags */ + varlink__doc__, /* tp_doc */ + 0, /* tp_traverse */ + 0, /* tp_clear */ + 0, /* tp_richcompare */ + 0, /* tp_weaklistoffset */ +#if PY_VERSION_HEX >= 0x02020000 + 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, /* tp_iter -> tp_weaklist */ +#endif +#if PY_VERSION_HEX >= 0x02030000 + 0, /* tp_del */ +#endif +#if PY_VERSION_HEX >= 0x02060000 + 0, /* tp_version */ +#endif +#ifdef COUNT_ALLOCS + 0,0,0,0 /* tp_alloc -> tp_next */ +#endif + }; + varlink_type = tmp; + type_init = 1; +#if PY_VERSION_HEX < 0x02020000 + varlink_type.ob_type = &PyType_Type; +#else + if (PyType_Ready(&varlink_type) < 0) + return NULL; +#endif + } + return &varlink_type; + } + + /* Create a variable linking object for use later */ + SWIGINTERN PyObject * + SWIG_Python_newvarlink(void) { + swig_varlinkobject *result = PyObject_NEW(swig_varlinkobject, swig_varlink_type()); + if (result) { + result->vars = 0; + } + return ((PyObject*) result); + } + + SWIGINTERN void + SWIG_Python_addvarlink(PyObject *p, char *name, PyObject *(*get_attr)(void), int (*set_attr)(PyObject *p)) { + swig_varlinkobject *v = (swig_varlinkobject *) p; + swig_globalvar *gv = (swig_globalvar *) malloc(sizeof(swig_globalvar)); + if (gv) { + size_t size = strlen(name)+1; + gv->name = (char *)malloc(size); + if (gv->name) { + strncpy(gv->name,name,size); + gv->get_attr = get_attr; + gv->set_attr = set_attr; + gv->next = v->vars; + } + } + v->vars = gv; + } + + SWIGINTERN PyObject * + SWIG_globals(void) { + static PyObject *_SWIG_globals = 0; + if (!_SWIG_globals) _SWIG_globals = SWIG_newvarlink(); + return _SWIG_globals; + } + + /* ----------------------------------------------------------------------------- + * constants/methods manipulation + * ----------------------------------------------------------------------------- */ + + /* Install Constants */ + SWIGINTERN void + SWIG_Python_InstallConstants(PyObject *d, swig_const_info constants[]) { + PyObject *obj = 0; + size_t i; + for (i = 0; constants[i].type; ++i) { + switch(constants[i].type) { + case SWIG_PY_POINTER: + obj = SWIG_InternalNewPointerObj(constants[i].pvalue, *(constants[i]).ptype,0); + break; + case SWIG_PY_BINARY: + obj = SWIG_NewPackedObj(constants[i].pvalue, constants[i].lvalue, *(constants[i].ptype)); + break; + default: + obj = 0; + break; + } + if (obj) { + PyDict_SetItemString(d, constants[i].name, obj); + Py_DECREF(obj); + } + } + } + + /* -----------------------------------------------------------------------------*/ + /* Fix SwigMethods to carry the callback ptrs when needed */ + /* -----------------------------------------------------------------------------*/ + + SWIGINTERN void + SWIG_Python_FixMethods(PyMethodDef *methods, + swig_const_info *const_table, + swig_type_info **types, + swig_type_info **types_initial) { + size_t i; + for (i = 0; methods[i].ml_name; ++i) { + const char *c = methods[i].ml_doc; + if (c && (c = strstr(c, "swig_ptr: "))) { + int j; + swig_const_info *ci = 0; + const char *name = c + 10; + for (j = 0; const_table[j].type; ++j) { + if (strncmp(const_table[j].name, name, + strlen(const_table[j].name)) == 0) { + ci = &(const_table[j]); + break; + } + } + if (ci) { + void *ptr = (ci->type == SWIG_PY_POINTER) ? ci->pvalue : 0; + if (ptr) { + size_t shift = (ci->ptype) - types; + swig_type_info *ty = types_initial[shift]; + size_t ldoc = (c - methods[i].ml_doc); + size_t lptr = strlen(ty->name)+2*sizeof(void*)+2; + char *ndoc = (char*)malloc(ldoc + lptr + 10); + if (ndoc) { + char *buff = ndoc; + strncpy(buff, methods[i].ml_doc, ldoc); + buff += ldoc; + strncpy(buff, "swig_ptr: ", 10); + buff += 10; + SWIG_PackVoidPtr(buff, ptr, ty->name, lptr); + methods[i].ml_doc = ndoc; + } + } + } + } + } + } + +#ifdef __cplusplus +} +#endif + +/* -----------------------------------------------------------------------------* + * Partial Init method + * -----------------------------------------------------------------------------*/ + +#ifdef __cplusplus +extern "C" +#endif + +SWIGEXPORT +#if PY_VERSION_HEX >= 0x03000000 +PyObject* +#else +void +#endif +SWIG_init(void) { + PyObject *m, *d, *md; +#if PY_VERSION_HEX >= 0x03000000 + static struct PyModuleDef SWIG_module = { +# if PY_VERSION_HEX >= 0x03020000 + PyModuleDef_HEAD_INIT, +# else + { + PyObject_HEAD_INIT(NULL) + NULL, /* m_init */ + 0, /* m_index */ + NULL, /* m_copy */ + }, +# endif + (char *) SWIG_name, + NULL, + -1, + SwigMethods, + NULL, + NULL, + NULL, + NULL + }; +#endif + +#if defined(SWIGPYTHON_BUILTIN) + static SwigPyClientData SwigPyObject_clientdata = { + 0, 0, 0, 0, 0, 0, 0 + }; + static PyGetSetDef this_getset_def = { + (char *)"this", &SwigPyBuiltin_ThisClosure, NULL, NULL, NULL + }; + static SwigPyGetSet thisown_getset_closure = { + (PyCFunction) SwigPyObject_own, + (PyCFunction) SwigPyObject_own + }; + static PyGetSetDef thisown_getset_def = { + (char *)"thisown", SwigPyBuiltin_GetterClosure, SwigPyBuiltin_SetterClosure, NULL, &thisown_getset_closure + }; + PyObject *metatype_args; + PyTypeObject *builtin_pytype; + int builtin_base_count; + swig_type_info *builtin_basetype; + PyObject *tuple; + PyGetSetDescrObject *static_getset; + PyTypeObject *metatype; + SwigPyClientData *cd; + PyObject *public_interface, *public_symbol; + PyObject *this_descr; + PyObject *thisown_descr; + int i; + + (void)builtin_pytype; + (void)builtin_base_count; + (void)builtin_basetype; + (void)tuple; + (void)static_getset; + + /* metatype is used to implement static member variables. */ + metatype_args = Py_BuildValue("(s(O){})", "SwigPyObjectType", &PyType_Type); + assert(metatype_args); + metatype = (PyTypeObject *) PyType_Type.tp_call((PyObject *) &PyType_Type, metatype_args, NULL); + assert(metatype); + Py_DECREF(metatype_args); + metatype->tp_setattro = (setattrofunc) &SwigPyObjectType_setattro; + assert(PyType_Ready(metatype) >= 0); +#endif + + /* Fix SwigMethods to carry the callback ptrs when needed */ + SWIG_Python_FixMethods(SwigMethods, swig_const_table, swig_types, swig_type_initial); + +#if PY_VERSION_HEX >= 0x03000000 + m = PyModule_Create(&SWIG_module); +#else + m = Py_InitModule((char *) SWIG_name, SwigMethods); +#endif + md = d = PyModule_GetDict(m); + (void)md; + + SWIG_InitializeModule(0); + +#ifdef SWIGPYTHON_BUILTIN + SwigPyObject_stype = SWIG_MangledTypeQuery("_p_SwigPyObject"); + assert(SwigPyObject_stype); + cd = (SwigPyClientData*) SwigPyObject_stype->clientdata; + if (!cd) { + SwigPyObject_stype->clientdata = &SwigPyObject_clientdata; + SwigPyObject_clientdata.pytype = SwigPyObject_TypeOnce(); + } else if (SwigPyObject_TypeOnce()->tp_basicsize != cd->pytype->tp_basicsize) { + PyErr_SetString(PyExc_RuntimeError, "Import error: attempted to load two incompatible swig-generated modules."); +# if PY_VERSION_HEX >= 0x03000000 + return NULL; +# else + return; +# endif + } + + /* All objects have a 'this' attribute */ + this_descr = PyDescr_NewGetSet(SwigPyObject_type(), &this_getset_def); + (void)this_descr; + + /* All objects have a 'thisown' attribute */ + thisown_descr = PyDescr_NewGetSet(SwigPyObject_type(), &thisown_getset_def); + (void)thisown_descr; + + public_interface = PyList_New(0); + public_symbol = 0; + (void)public_symbol; + + PyDict_SetItemString(md, "__all__", public_interface); + Py_DECREF(public_interface); + for (i = 0; SwigMethods[i].ml_name != NULL; ++i) + SwigPyBuiltin_AddPublicSymbol(public_interface, SwigMethods[i].ml_name); + for (i = 0; swig_const_table[i].name != 0; ++i) + SwigPyBuiltin_AddPublicSymbol(public_interface, swig_const_table[i].name); +#endif + + SWIG_InstallConstants(d,swig_const_table); + + + /* Initialize threading */ + SWIG_PYTHON_INITIALIZE_THREADS; +#if PY_VERSION_HEX >= 0x03000000 + return m; +#else + return; +#endif +} + diff --git a/libs/esl/python3/events.py b/libs/esl/python3/events.py new file mode 100644 index 0000000000..2c59043447 --- /dev/null +++ b/libs/esl/python3/events.py @@ -0,0 +1,20 @@ +#!/usr/bin/env python + +import string +import sys + +from ESL import * + +con = ESLconnection("localhost","8021","ClueCon") +#are we connected? + +if con.connected: + + con.events("plain", "all"); + + while 1: + #my $e = $con->recvEventTimed(100); + e = con.recvEvent() + + if e: + print e.serialize() diff --git a/libs/esl/python3/python-config b/libs/esl/python3/python-config new file mode 100644 index 0000000000..cb4a6eff0a --- /dev/null +++ b/libs/esl/python3/python-config @@ -0,0 +1,55 @@ +#!/usr/bin/env python3 + +from __future__ import print_function +import sys +import os +import getopt +from distutils import sysconfig + +valid_opts = ['prefix', 'exec-prefix', 'includes', 'libs', 'cflags', + 'ldflags', 'help'] + +def exit_with_usage(code=1): + print("Usage: %s [%s]" % (sys.argv[0], '|'.join('--'+opt for opt in valid_opts)), file=sys.stderr) + sys.exit(code) + +try: + opts, args = getopt.getopt(sys.argv[1:], '', valid_opts) +except getopt.error: + exit_with_usage() + +if not opts: + exit_with_usage() + +opt = opts[0][0] + +pyver = sysconfig.get_config_var('LDVERSION') +if pyver == None: + pyver = sysconfig.get_config_var('VERSION') +getvar = sysconfig.get_config_var + +if opt == '--help': + exit_with_usage(0) + +elif opt == '--prefix': + print(sysconfig.PREFIX) + +elif opt == '--exec-prefix': + print(sysconfig.EXEC_PREFIX) + +elif opt in ('--includes', '--cflags'): + flags = ['-I' + sysconfig.get_python_inc(), + '-I' + sysconfig.get_python_inc(plat_specific=True)] + if opt == '--cflags': + flags.extend(getvar('CFLAGS').split()) + print(' '.join(flags)) + +elif opt in ('--libs', '--ldflags'): + libs = getvar('LIBS').split() + getvar('SYSLIBS').split() + libs.append('-lpython'+pyver) + # add the prefix/lib/pythonX.Y/config dir, but only if there is no + # shared library in prefix/lib/. + if opt == '--ldflags' and not getvar('Py_ENABLE_SHARED'): + libs.insert(0, '-L' + getvar('LIBPL')) + print(' '.join(libs)) + diff --git a/libs/esl/python3/server.py b/libs/esl/python3/server.py new file mode 100644 index 0000000000..deba5f2ab9 --- /dev/null +++ b/libs/esl/python3/server.py @@ -0,0 +1,29 @@ +#!/usr/bin/env python + +import SocketServer +from ESL import * + +class ESLRequestHandler(SocketServer.BaseRequestHandler ): + def setup(self): + print self.client_address, 'connected!' + + fd = self.request.fileno() + print fd + + con = ESLconnection(fd) + print "Connected: " + print con.connected() + if con.connected(): + + info = con.getInfo() + + uuid = info.getHeader("unique-id") + print uuid + con.execute("answer", "", uuid) + con.execute("playback", "/ram/swimp.raw", uuid); + +#server host is a tuple ('host', port) +server = SocketServer.ThreadingTCPServer(('', 8040), ESLRequestHandler) +server.serve_forever() + + diff --git a/libs/esl/python3/single_command.py b/libs/esl/python3/single_command.py new file mode 100644 index 0000000000..c47c57c13c --- /dev/null +++ b/libs/esl/python3/single_command.py @@ -0,0 +1,43 @@ +#!/usr/bin/env python + +import string +import sys +from optparse import OptionParser +from ESL import * + +def main(argv): + + try: + + parser = OptionParser() + parser.add_option("-a", "--auth", dest="auth", default="ClueCon", + help="ESL password") + parser.add_option("-s", "--server", dest="server", default="127.0.0.1", + help="FreeSWITCH server IP address") + parser.add_option("-p", "--port", dest="port", default="8021", + help="FreeSWITCH server event socket port") + parser.add_option("-c", "--command", dest="command", + help="command to run, surround mutli word commands in \"\'s") + + (options, args) = parser.parse_args() + + + con = ESLconnection(options.server, options.port, options.auth) + #are we connected? + + if con.connected(): + #run command + e = con.api(options.command) + print e.getBody() + + else: + + print "Not Connected" + sys.exit(2) + + except: + + print parser.get_usage() + +if __name__ == "__main__": + main(sys.argv[1:]) \ No newline at end of file diff --git a/libs/esl/src/esl_event.c b/libs/esl/src/esl_event.c index 68e0688114..cca7899d80 100644 --- a/libs/esl/src/esl_event.c +++ b/libs/esl/src/esl_event.c @@ -132,6 +132,7 @@ static const char *EVENT_NAMES[] = { "SEND_INFO", "RECV_INFO", "RECV_RTCP_MESSAGE", + "SEND_RTCP_MESSAGE", "CALL_SECURE", "NAT", "RECORD_START", @@ -483,11 +484,14 @@ static esl_status_t esl_event_base_add_header(esl_event_t *event, esl_stack_t st exists = 1; } + FREE(data); goto redraw; } } else if (tmp_header) { free_header(&tmp_header); } + + FREE(data); goto end; } else { if ((stack & ESL_STACK_PUSH) || (stack & ESL_STACK_UNSHIFT)) { diff --git a/libs/esl/src/include/esl_event.h b/libs/esl/src/include/esl_event.h index de070ad723..01e7ada07e 100644 --- a/libs/esl/src/include/esl_event.h +++ b/libs/esl/src/include/esl_event.h @@ -120,6 +120,7 @@ typedef enum { ESL_EVENT_SEND_INFO, ESL_EVENT_RECV_INFO, ESL_EVENT_RECV_RTCP_MESSAGE, + ESL_EVENT_SEND_RTCP_MESSAGE, ESL_EVENT_CALL_SECURE, ESL_EVENT_NAT, ESL_EVENT_RECORD_START, diff --git a/libs/iksemel/tools/iksroster.c b/libs/iksemel/tools/iksroster.c index 144f3de189..e97f81cd15 100644 --- a/libs/iksemel/tools/iksroster.c +++ b/libs/iksemel/tools/iksroster.c @@ -374,6 +374,6 @@ main (int argc, char *argv[]) #ifdef _WIN32 WSACleanup (); #endif - + if (file) free(file); return 0; } diff --git a/libs/libdingaling/src/libdingaling.c b/libs/libdingaling/src/libdingaling.c index 6fbedfda6e..ee08f041c0 100644 --- a/libs/libdingaling/src/libdingaling.c +++ b/libs/libdingaling/src/libdingaling.c @@ -1297,6 +1297,8 @@ static int on_subscribe(void *user_data, ikspak *pak) handle->session_callback(handle, NULL, LDL_SIGNAL_SUBSCRIBE, to, from, NULL, NULL); } + if (id) free(id); + return IKS_FILTER_EAT; } @@ -2325,6 +2327,9 @@ void ldl_handle_send_msg(ldl_handle_t *handle, char *from, char *to, const char if (strchr(my_body, '<')) { len = (int) strlen(my_body); if (!(bdup = malloc(len))) { + if (my_body_base) { + free(my_body_base); + } return; } diff --git a/libs/libvpx/build/make/configure.sh b/libs/libvpx/build/make/configure.sh index 728c3e2568..b1f7804a59 100644 --- a/libs/libvpx/build/make/configure.sh +++ b/libs/libvpx/build/make/configure.sh @@ -865,7 +865,11 @@ process_common_toolchain() { case ${toolchain} in *-darwin-*) mvmin=$(sw_vers -productVersion) - mvmin="-mmacosx-version-min="${mvmin%.*} + if [[ $mvmin == 10.* ]]; then + mvmin="-mmacosx-version-min=""${mvmin%.*}" + else + mvmin="-mmacosx-version-min=""${mvmin%%.*}" + fi add_cflags $mvmin add_ldflags $mvmin ;; diff --git a/libs/libvpx/vp8/encoder/pickinter.c b/libs/libvpx/vp8/encoder/pickinter.c index dc72eed88c..6f8a173582 100644 --- a/libs/libvpx/vp8/encoder/pickinter.c +++ b/libs/libvpx/vp8/encoder/pickinter.c @@ -631,16 +631,16 @@ void vp8_pick_inter_mode(VP8_COMP *cpi, MACROBLOCK *x, int recon_yoffset, } #endif assert(plane[LAST_FRAME][0] != NULL); - dot_artifact_candidate = check_dot_artifact_candidate( + if (plane[LAST_FRAME][0]) dot_artifact_candidate = check_dot_artifact_candidate( cpi, x, target_y, stride, plane[LAST_FRAME][0], mb_row, mb_col, 0); // If not found in Y channel, check UV channel. if (!dot_artifact_candidate) { assert(plane[LAST_FRAME][1] != NULL); - dot_artifact_candidate = check_dot_artifact_candidate( + if (plane[LAST_FRAME][1]) dot_artifact_candidate = check_dot_artifact_candidate( cpi, x, target_u, stride_uv, plane[LAST_FRAME][1], mb_row, mb_col, 1); if (!dot_artifact_candidate) { assert(plane[LAST_FRAME][2] != NULL); - dot_artifact_candidate = check_dot_artifact_candidate( + if (plane[LAST_FRAME][2]) dot_artifact_candidate = check_dot_artifact_candidate( cpi, x, target_v, stride_uv, plane[LAST_FRAME][2], mb_row, mb_col, 2); } diff --git a/libs/libvpx/vp9/encoder/vp9_subexp.c b/libs/libvpx/vp9/encoder/vp9_subexp.c index 19bbd5373f..cf17fcdfce 100644 --- a/libs/libvpx/vp9/encoder/vp9_subexp.c +++ b/libs/libvpx/vp9/encoder/vp9_subexp.c @@ -72,7 +72,7 @@ static int remap_prob(int v, int m) { i = recenter_nonneg(MAX_PROB - 1 - v, MAX_PROB - 1 - m) - 1; assert(i >= 0 && (size_t)i < sizeof(map_table)); - i = map_table[i]; + if (i >= 0 && (size_t)i < sizeof(map_table)) i = map_table[i]; return i; } diff --git a/libs/libyuv/source/scale.cc b/libs/libyuv/source/scale.cc index ab08549637..30066d5b34 100644 --- a/libs/libyuv/source/scale.cc +++ b/libs/libyuv/source/scale.cc @@ -736,6 +736,9 @@ static void ScaleAddCols2_C(int dst_width, int dx, const uint16_t* src_ptr, uint8_t* dst_ptr) { +#ifdef __clang_analyzer__ + *dst_ptr = 0; +#else int i; int scaletbl[2]; int minboxwidth = dx >> 16; @@ -750,6 +753,7 @@ static void ScaleAddCols2_C(int dst_width, SumPixels(boxwidth, src_ptr + ix) * scaletbl[boxwidth - minboxwidth] >> 16; } +#endif } static void ScaleAddCols2_16_C(int dst_width, @@ -758,6 +762,9 @@ static void ScaleAddCols2_16_C(int dst_width, int dx, const uint32_t* src_ptr, uint16_t* dst_ptr) { +#ifdef __clang_analyzer__ + * dst_ptr = 0; +#else int i; int scaletbl[2]; int minboxwidth = dx >> 16; @@ -772,6 +779,7 @@ static void ScaleAddCols2_16_C(int dst_width, scaletbl[boxwidth - minboxwidth] >> 16; } +#endif } static void ScaleAddCols0_C(int dst_width, diff --git a/libs/srtp/config_in.h b/libs/srtp/config_in.h deleted file mode 100644 index 31e6ffe385..0000000000 --- a/libs/srtp/config_in.h +++ /dev/null @@ -1,196 +0,0 @@ -/* config_in.h. Generated from configure.ac by autoheader. */ - -/* Define if building universal (internal helper macro) */ -#undef AC_APPLE_UNIVERSAL_BUILD - -/* Define if building for a CISC machine (e.g. Intel). */ -#undef CPU_CISC - -/* Define if building for a RISC machine (assume slow byte access). */ -#undef CPU_RISC - -/* Define to enabled debug logging for all mudules. */ -#undef ENABLE_DEBUG_LOGGING - -/* Logging statments will be writen to this file. */ -#undef ERR_REPORTING_FILE - -/* Define to redirect logging to stdout. */ -#undef ERR_REPORTING_STDOUT - -/* Define this to use AES-GCM. */ -#undef GCM - -/* Define to 1 if you have the header file. */ -#undef HAVE_ARPA_INET_H - -/* Define to 1 if you have the header file. */ -#undef HAVE_BYTESWAP_H - -/* Define to 1 if you have the `inet_aton' function. */ -#undef HAVE_INET_ATON - -/* Define to 1 if the system has the type `int16_t'. */ -#undef HAVE_INT16_T - -/* Define to 1 if the system has the type `int32_t'. */ -#undef HAVE_INT32_T - -/* Define to 1 if the system has the type `int8_t'. */ -#undef HAVE_INT8_T - -/* Define to 1 if you have the header file. */ -#undef HAVE_INTTYPES_H - -/* Define to 1 if you have the `dl' library (-ldl). */ -#undef HAVE_LIBDL - -/* Define to 1 if you have the `nspr4' library (-lnspr4). */ -#undef HAVE_LIBNSPR4 - -/* Define to 1 if you have the `nss3' library (-lnss3). */ -#undef HAVE_LIBNSS3 - -/* Define to 1 if you have the `socket' library (-lsocket). */ -#undef HAVE_LIBSOCKET - -/* Define to 1 if you have the `z' library (-lz). */ -#undef HAVE_LIBZ - -/* Define to 1 if you have the header file. */ -#undef HAVE_MACHINE_TYPES_H - -/* Define to 1 if you have the header file. */ -#undef HAVE_MEMORY_H - -/* Define to 1 if you have the header file. */ -#undef HAVE_NETINET_IN_H - -/* Define to 1 if you have the header file. */ -#undef HAVE_NSS_H - -/* Define to 1 if you have the `winpcap' library (-lwpcap) */ -#undef HAVE_PCAP - -/* Define to 1 if you have the `sigaction' function. */ -#undef HAVE_SIGACTION - -/* Define to 1 if you have the `socket' function. */ -#undef HAVE_SOCKET - -/* Define to 1 if you have the header file. */ -#undef HAVE_STDINT_H - -/* Define to 1 if you have the header file. */ -#undef HAVE_STDLIB_H - -/* Define to 1 if you have the header file. */ -#undef HAVE_STRINGS_H - -/* Define to 1 if you have the header file. */ -#undef HAVE_STRING_H - -/* Define to 1 if you have the header file. */ -#undef HAVE_SYS_INT_TYPES_H - -/* Define to 1 if you have the header file. */ -#undef HAVE_SYS_SOCKET_H - -/* Define to 1 if you have the header file. */ -#undef HAVE_SYS_STAT_H - -/* Define to 1 if you have the header file. */ -#undef HAVE_SYS_TYPES_H - -/* Define to 1 if you have the header file. */ -#undef HAVE_SYS_UIO_H - -/* Define to 1 if the system has the type `uint16_t'. */ -#undef HAVE_UINT16_T - -/* Define to 1 if the system has the type `uint32_t'. */ -#undef HAVE_UINT32_T - -/* Define to 1 if the system has the type `uint64_t'. */ -#undef HAVE_UINT64_T - -/* Define to 1 if the system has the type `uint8_t'. */ -#undef HAVE_UINT8_T - -/* Define to 1 if you have the header file. */ -#undef HAVE_UNISTD_H - -/* Define to 1 if you have the `usleep' function. */ -#undef HAVE_USLEEP - -/* Define to 1 if you have the header file. */ -#undef HAVE_WINDOWS_H - -/* Define to 1 if you have the header file. */ -#undef HAVE_WINSOCK2_H - -/* Define to use X86 inlined assembly code */ -#undef HAVE_X86 - -/* Define this to use NSS crypto. */ -#undef NSS - -/* Define this to use OpenSSL crypto. */ -#undef OPENSSL - -/* Define this if OPENSSL_cleanse is broken. */ -#undef OPENSSL_CLEANSE_BROKEN - -/* Define this to use OpenSSL KDF for SRTP. */ -#undef OPENSSL_KDF - -/* Define to the address where bug reports for this package should be sent. */ -#undef PACKAGE_BUGREPORT - -/* Define to the full name of this package. */ -#undef PACKAGE_NAME - -/* Define to the full name and version of this package. */ -#undef PACKAGE_STRING - -/* Define to the one symbol short name of this package. */ -#undef PACKAGE_TARNAME - -/* Define to the home page for this package. */ -#undef PACKAGE_URL - -/* Define to the version of this package. */ -#undef PACKAGE_VERSION - -/* The size of `unsigned long', as computed by sizeof. */ -#undef SIZEOF_UNSIGNED_LONG - -/* The size of `unsigned long long', as computed by sizeof. */ -#undef SIZEOF_UNSIGNED_LONG_LONG - -/* Define to 1 if you have the ANSI C header files. */ -#undef STDC_HEADERS - -/* Define WORDS_BIGENDIAN to 1 if your processor stores words with the most - significant byte first (like Motorola and SPARC, unlike Intel). */ -#if defined AC_APPLE_UNIVERSAL_BUILD -# if defined __BIG_ENDIAN__ -# define WORDS_BIGENDIAN 1 -# endif -#else -# ifndef WORDS_BIGENDIAN -# undef WORDS_BIGENDIAN -# endif -#endif - -/* Define to empty if `const' does not conform to ANSI C. */ -#undef const - -/* Define to `__inline__' or `__inline' if that's what the C compiler - calls it, or to nothing if 'inline' is not supported under any name. */ -#ifndef __cplusplus -#undef inline -#endif - -/* Define to `unsigned int' if does not define. */ -#undef size_t diff --git a/libs/srtp/crypto/include/datatypes.h b/libs/srtp/crypto/include/datatypes.h index 5164cf0021..55bcd73855 100644 --- a/libs/srtp/crypto/include/datatypes.h +++ b/libs/srtp/crypto/include/datatypes.h @@ -168,7 +168,7 @@ void octet_string_set_to_zero(void *s, size_t len); #define be64_to_cpu(x) bswap_64((x)) #else /* WORDS_BIGENDIAN */ -#if defined(__GNUC__) && (defined(HAVE_X86) || defined(__x86_64__)) +#if defined(__GNUC__) && defined(HAVE_X86) /* Fall back. */ static inline uint32_t be32_to_cpu(uint32_t v) { diff --git a/libs/stb/stb_image.h b/libs/stb/stb_image.h new file mode 100644 index 0000000000..0ea47afd9f --- /dev/null +++ b/libs/stb/stb_image.h @@ -0,0 +1,7656 @@ +/* stb_image - v2.25 - public domain image loader - http://nothings.org/stb + no warranty implied; use at your own risk + + Do this: + #define STB_IMAGE_IMPLEMENTATION + before you include this file in *one* C or C++ file to create the implementation. + + // i.e. it should look like this: + #include ... + #include ... + #include ... + #define STB_IMAGE_IMPLEMENTATION + #include "stb_image.h" + + You can #define STBI_ASSERT(x) before the #include to avoid using assert.h. + And #define STBI_MALLOC, STBI_REALLOC, and STBI_FREE to avoid using malloc,realloc,free + + + QUICK NOTES: + Primarily of interest to game developers and other people who can + avoid problematic images and only need the trivial interface + + JPEG baseline & progressive (12 bpc/arithmetic not supported, same as stock IJG lib) + PNG 1/2/4/8/16-bit-per-channel + + TGA (not sure what subset, if a subset) + BMP non-1bpp, non-RLE + PSD (composited view only, no extra channels, 8/16 bit-per-channel) + + GIF (*comp always reports as 4-channel) + HDR (radiance rgbE format) + PIC (Softimage PIC) + PNM (PPM and PGM binary only) + + Animated GIF still needs a proper API, but here's one way to do it: + http://gist.github.com/urraka/685d9a6340b26b830d49 + + - decode from memory or through FILE (define STBI_NO_STDIO to remove code) + - decode from arbitrary I/O callbacks + - SIMD acceleration on x86/x64 (SSE2) and ARM (NEON) + + Full documentation under "DOCUMENTATION" below. + + +LICENSE + + See end of file for license information. + +RECENT REVISION HISTORY: + + 2.25 (2020-02-02) fix warnings + 2.24 (2020-02-02) fix warnings; thread-local failure_reason and flip_vertically + 2.23 (2019-08-11) fix clang static analysis warning + 2.22 (2019-03-04) gif fixes, fix warnings + 2.21 (2019-02-25) fix typo in comment + 2.20 (2019-02-07) support utf8 filenames in Windows; fix warnings and platform ifdefs + 2.19 (2018-02-11) fix warning + 2.18 (2018-01-30) fix warnings + 2.17 (2018-01-29) bugfix, 1-bit BMP, 16-bitness query, fix warnings + 2.16 (2017-07-23) all functions have 16-bit variants; optimizations; bugfixes + 2.15 (2017-03-18) fix png-1,2,4; all Imagenet JPGs; no runtime SSE detection on GCC + 2.14 (2017-03-03) remove deprecated STBI_JPEG_OLD; fixes for Imagenet JPGs + 2.13 (2016-12-04) experimental 16-bit API, only for PNG so far; fixes + 2.12 (2016-04-02) fix typo in 2.11 PSD fix that caused crashes + 2.11 (2016-04-02) 16-bit PNGS; enable SSE2 in non-gcc x64 + RGB-format JPEG; remove white matting in PSD; + allocate large structures on the stack; + correct channel count for PNG & BMP + 2.10 (2016-01-22) avoid warning introduced in 2.09 + 2.09 (2016-01-16) 16-bit TGA; comments in PNM files; STBI_REALLOC_SIZED + + See end of file for full revision history. + + + ============================ Contributors ========================= + + Image formats Extensions, features + Sean Barrett (jpeg, png, bmp) Jetro Lauha (stbi_info) + Nicolas Schulz (hdr, psd) Martin "SpartanJ" Golini (stbi_info) + Jonathan Dummer (tga) James "moose2000" Brown (iPhone PNG) + Jean-Marc Lienher (gif) Ben "Disch" Wenger (io callbacks) + Tom Seddon (pic) Omar Cornut (1/2/4-bit PNG) + Thatcher Ulrich (psd) Nicolas Guillemot (vertical flip) + Ken Miller (pgm, ppm) Richard Mitton (16-bit PSD) + github:urraka (animated gif) Junggon Kim (PNM comments) + Christopher Forseth (animated gif) Daniel Gibson (16-bit TGA) + socks-the-fox (16-bit PNG) + Jeremy Sawicki (handle all ImageNet JPGs) + Optimizations & bugfixes Mikhail Morozov (1-bit BMP) + Fabian "ryg" Giesen Anael Seghezzi (is-16-bit query) + Arseny Kapoulkine + John-Mark Allen + Carmelo J Fdez-Aguera + + Bug & warning fixes + Marc LeBlanc David Woo Guillaume George Martins Mozeiko + Christpher Lloyd Jerry Jansson Joseph Thomson Phil Jordan + Dave Moore Roy Eltham Hayaki Saito Nathan Reed + Won Chun Luke Graham Johan Duparc Nick Verigakis + the Horde3D community Thomas Ruf Ronny Chevalier github:rlyeh + Janez Zemva John Bartholomew Michal Cichon github:romigrou + Jonathan Blow Ken Hamada Tero Hanninen github:svdijk + Laurent Gomila Cort Stratton Sergio Gonzalez github:snagar + Aruelien Pocheville Thibault Reuille Cass Everitt github:Zelex + Ryamond Barbiero Paul Du Bois Engin Manap github:grim210 + Aldo Culquicondor Philipp Wiesemann Dale Weiler github:sammyhw + Oriol Ferrer Mesia Josh Tobin Matthew Gregan github:phprus + Julian Raschke Gregory Mullen Baldur Karlsson github:poppolopoppo + Christian Floisand Kevin Schmidt JR Smith github:darealshinji + Brad Weinberger Matvey Cherevko github:Michaelangel007 + Blazej Dariusz Roszkowski Alexander Veselov +*/ + +#ifndef STBI_INCLUDE_STB_IMAGE_H +#define STBI_INCLUDE_STB_IMAGE_H + +// DOCUMENTATION +// +// Limitations: +// - no 12-bit-per-channel JPEG +// - no JPEGs with arithmetic coding +// - GIF always returns *comp=4 +// +// Basic usage (see HDR discussion below for HDR usage): +// int x,y,n; +// unsigned char *data = stbi_load(filename, &x, &y, &n, 0); +// // ... process data if not NULL ... +// // ... x = width, y = height, n = # 8-bit components per pixel ... +// // ... replace '0' with '1'..'4' to force that many components per pixel +// // ... but 'n' will always be the number that it would have been if you said 0 +// stbi_image_free(data) +// +// Standard parameters: +// int *x -- outputs image width in pixels +// int *y -- outputs image height in pixels +// int *channels_in_file -- outputs # of image components in image file +// int desired_channels -- if non-zero, # of image components requested in result +// +// The return value from an image loader is an 'unsigned char *' which points +// to the pixel data, or NULL on an allocation failure or if the image is +// corrupt or invalid. The pixel data consists of *y scanlines of *x pixels, +// with each pixel consisting of N interleaved 8-bit components; the first +// pixel pointed to is top-left-most in the image. There is no padding between +// image scanlines or between pixels, regardless of format. The number of +// components N is 'desired_channels' if desired_channels is non-zero, or +// *channels_in_file otherwise. If desired_channels is non-zero, +// *channels_in_file has the number of components that _would_ have been +// output otherwise. E.g. if you set desired_channels to 4, you will always +// get RGBA output, but you can check *channels_in_file to see if it's trivially +// opaque because e.g. there were only 3 channels in the source image. +// +// An output image with N components has the following components interleaved +// in this order in each pixel: +// +// N=#comp components +// 1 grey +// 2 grey, alpha +// 3 red, green, blue +// 4 red, green, blue, alpha +// +// If image loading fails for any reason, the return value will be NULL, +// and *x, *y, *channels_in_file will be unchanged. The function +// stbi_failure_reason() can be queried for an extremely brief, end-user +// unfriendly explanation of why the load failed. Define STBI_NO_FAILURE_STRINGS +// to avoid compiling these strings at all, and STBI_FAILURE_USERMSG to get slightly +// more user-friendly ones. +// +// Paletted PNG, BMP, GIF, and PIC images are automatically depalettized. +// +// =========================================================================== +// +// UNICODE: +// +// If compiling for Windows and you wish to use Unicode filenames, compile +// with +// #define STBI_WINDOWS_UTF8 +// and pass utf8-encoded filenames. Call stbi_convert_wchar_to_utf8 to convert +// Windows wchar_t filenames to utf8. +// +// =========================================================================== +// +// Philosophy +// +// stb libraries are designed with the following priorities: +// +// 1. easy to use +// 2. easy to maintain +// 3. good performance +// +// Sometimes I let "good performance" creep up in priority over "easy to maintain", +// and for best performance I may provide less-easy-to-use APIs that give higher +// performance, in addition to the easy-to-use ones. Nevertheless, it's important +// to keep in mind that from the standpoint of you, a client of this library, +// all you care about is #1 and #3, and stb libraries DO NOT emphasize #3 above all. +// +// Some secondary priorities arise directly from the first two, some of which +// provide more explicit reasons why performance can't be emphasized. +// +// - Portable ("ease of use") +// - Small source code footprint ("easy to maintain") +// - No dependencies ("ease of use") +// +// =========================================================================== +// +// I/O callbacks +// +// I/O callbacks allow you to read from arbitrary sources, like packaged +// files or some other source. Data read from callbacks are processed +// through a small internal buffer (currently 128 bytes) to try to reduce +// overhead. +// +// The three functions you must define are "read" (reads some bytes of data), +// "skip" (skips some bytes of data), "eof" (reports if the stream is at the end). +// +// =========================================================================== +// +// SIMD support +// +// The JPEG decoder will try to automatically use SIMD kernels on x86 when +// supported by the compiler. For ARM Neon support, you must explicitly +// request it. +// +// (The old do-it-yourself SIMD API is no longer supported in the current +// code.) +// +// On x86, SSE2 will automatically be used when available based on a run-time +// test; if not, the generic C versions are used as a fall-back. On ARM targets, +// the typical path is to have separate builds for NEON and non-NEON devices +// (at least this is true for iOS and Android). Therefore, the NEON support is +// toggled by a build flag: define STBI_NEON to get NEON loops. +// +// If for some reason you do not want to use any of SIMD code, or if +// you have issues compiling it, you can disable it entirely by +// defining STBI_NO_SIMD. +// +// =========================================================================== +// +// HDR image support (disable by defining STBI_NO_HDR) +// +// stb_image supports loading HDR images in general, and currently the Radiance +// .HDR file format specifically. You can still load any file through the existing +// interface; if you attempt to load an HDR file, it will be automatically remapped +// to LDR, assuming gamma 2.2 and an arbitrary scale factor defaulting to 1; +// both of these constants can be reconfigured through this interface: +// +// stbi_hdr_to_ldr_gamma(2.2f); +// stbi_hdr_to_ldr_scale(1.0f); +// +// (note, do not use _inverse_ constants; stbi_image will invert them +// appropriately). +// +// Additionally, there is a new, parallel interface for loading files as +// (linear) floats to preserve the full dynamic range: +// +// float *data = stbi_loadf(filename, &x, &y, &n, 0); +// +// If you load LDR images through this interface, those images will +// be promoted to floating point values, run through the inverse of +// constants corresponding to the above: +// +// stbi_ldr_to_hdr_scale(1.0f); +// stbi_ldr_to_hdr_gamma(2.2f); +// +// Finally, given a filename (or an open file or memory block--see header +// file for details) containing image data, you can query for the "most +// appropriate" interface to use (that is, whether the image is HDR or +// not), using: +// +// stbi_is_hdr(char *filename); +// +// =========================================================================== +// +// iPhone PNG support: +// +// By default we convert iphone-formatted PNGs back to RGB, even though +// they are internally encoded differently. You can disable this conversion +// by calling stbi_convert_iphone_png_to_rgb(0), in which case +// you will always just get the native iphone "format" through (which +// is BGR stored in RGB). +// +// Call stbi_set_unpremultiply_on_load(1) as well to force a divide per +// pixel to remove any premultiplied alpha *only* if the image file explicitly +// says there's premultiplied data (currently only happens in iPhone images, +// and only if iPhone convert-to-rgb processing is on). +// +// =========================================================================== +// +// ADDITIONAL CONFIGURATION +// +// - You can suppress implementation of any of the decoders to reduce +// your code footprint by #defining one or more of the following +// symbols before creating the implementation. +// +// STBI_NO_JPEG +// STBI_NO_PNG +// STBI_NO_BMP +// STBI_NO_PSD +// STBI_NO_TGA +// STBI_NO_GIF +// STBI_NO_HDR +// STBI_NO_PIC +// STBI_NO_PNM (.ppm and .pgm) +// +// - You can request *only* certain decoders and suppress all other ones +// (this will be more forward-compatible, as addition of new decoders +// doesn't require you to disable them explicitly): +// +// STBI_ONLY_JPEG +// STBI_ONLY_PNG +// STBI_ONLY_BMP +// STBI_ONLY_PSD +// STBI_ONLY_TGA +// STBI_ONLY_GIF +// STBI_ONLY_HDR +// STBI_ONLY_PIC +// STBI_ONLY_PNM (.ppm and .pgm) +// +// - If you use STBI_NO_PNG (or _ONLY_ without PNG), and you still +// want the zlib decoder to be available, #define STBI_SUPPORT_ZLIB +// + + +#ifndef STBI_NO_STDIO +#include +#endif // STBI_NO_STDIO + +#define STBI_VERSION 1 + +enum +{ + STBI_default = 0, // only used for desired_channels + + STBI_grey = 1, + STBI_grey_alpha = 2, + STBI_rgb = 3, + STBI_rgb_alpha = 4 +}; + +#include +typedef unsigned char stbi_uc; +typedef unsigned short stbi_us; + +#ifdef __cplusplus +extern "C" { +#endif + +#ifndef STBIDEF +#ifdef STB_IMAGE_STATIC +#define STBIDEF static +#else +#define STBIDEF extern +#endif +#endif + +////////////////////////////////////////////////////////////////////////////// +// +// PRIMARY API - works on images of any type +// + +// +// load image by filename, open file, or memory buffer +// + +typedef struct +{ + int (*read) (void *user,char *data,int size); // fill 'data' with 'size' bytes. return number of bytes actually read + void (*skip) (void *user,int n); // skip the next 'n' bytes, or 'unget' the last -n bytes if negative + int (*eof) (void *user); // returns nonzero if we are at end of file/data +} stbi_io_callbacks; + +//////////////////////////////////// +// +// 8-bits-per-channel interface +// + +STBIDEF stbi_uc *stbi_load_from_memory (stbi_uc const *buffer, int len , int *x, int *y, int *channels_in_file, int desired_channels); +STBIDEF stbi_uc *stbi_load_from_callbacks(stbi_io_callbacks const *clbk , void *user, int *x, int *y, int *channels_in_file, int desired_channels); + +#ifndef STBI_NO_STDIO +STBIDEF stbi_uc *stbi_load (char const *filename, int *x, int *y, int *channels_in_file, int desired_channels); +STBIDEF stbi_uc *stbi_load_from_file (FILE *f, int *x, int *y, int *channels_in_file, int desired_channels); +// for stbi_load_from_file, file pointer is left pointing immediately after image +#endif + +#ifndef STBI_NO_GIF +STBIDEF stbi_uc *stbi_load_gif_from_memory(stbi_uc const *buffer, int len, int **delays, int *x, int *y, int *z, int *comp, int req_comp); +#endif + +#ifdef STBI_WINDOWS_UTF8 +STBIDEF int stbi_convert_wchar_to_utf8(char *buffer, size_t bufferlen, const wchar_t* input); +#endif + +//////////////////////////////////// +// +// 16-bits-per-channel interface +// + +STBIDEF stbi_us *stbi_load_16_from_memory (stbi_uc const *buffer, int len, int *x, int *y, int *channels_in_file, int desired_channels); +STBIDEF stbi_us *stbi_load_16_from_callbacks(stbi_io_callbacks const *clbk, void *user, int *x, int *y, int *channels_in_file, int desired_channels); + +#ifndef STBI_NO_STDIO +STBIDEF stbi_us *stbi_load_16 (char const *filename, int *x, int *y, int *channels_in_file, int desired_channels); +STBIDEF stbi_us *stbi_load_from_file_16(FILE *f, int *x, int *y, int *channels_in_file, int desired_channels); +#endif + +//////////////////////////////////// +// +// float-per-channel interface +// +#ifndef STBI_NO_LINEAR + STBIDEF float *stbi_loadf_from_memory (stbi_uc const *buffer, int len, int *x, int *y, int *channels_in_file, int desired_channels); + STBIDEF float *stbi_loadf_from_callbacks (stbi_io_callbacks const *clbk, void *user, int *x, int *y, int *channels_in_file, int desired_channels); + + #ifndef STBI_NO_STDIO + STBIDEF float *stbi_loadf (char const *filename, int *x, int *y, int *channels_in_file, int desired_channels); + STBIDEF float *stbi_loadf_from_file (FILE *f, int *x, int *y, int *channels_in_file, int desired_channels); + #endif +#endif + +#ifndef STBI_NO_HDR + STBIDEF void stbi_hdr_to_ldr_gamma(float gamma); + STBIDEF void stbi_hdr_to_ldr_scale(float scale); +#endif // STBI_NO_HDR + +#ifndef STBI_NO_LINEAR + STBIDEF void stbi_ldr_to_hdr_gamma(float gamma); + STBIDEF void stbi_ldr_to_hdr_scale(float scale); +#endif // STBI_NO_LINEAR + +// stbi_is_hdr is always defined, but always returns false if STBI_NO_HDR +STBIDEF int stbi_is_hdr_from_callbacks(stbi_io_callbacks const *clbk, void *user); +STBIDEF int stbi_is_hdr_from_memory(stbi_uc const *buffer, int len); +#ifndef STBI_NO_STDIO +STBIDEF int stbi_is_hdr (char const *filename); +STBIDEF int stbi_is_hdr_from_file(FILE *f); +#endif // STBI_NO_STDIO + + +// get a VERY brief reason for failure +// on most compilers (and ALL modern mainstream compilers) this is threadsafe +STBIDEF const char *stbi_failure_reason (void); + +// free the loaded image -- this is just free() +STBIDEF void stbi_image_free (void *retval_from_stbi_load); + +// get image dimensions & components without fully decoding +STBIDEF int stbi_info_from_memory(stbi_uc const *buffer, int len, int *x, int *y, int *comp); +STBIDEF int stbi_info_from_callbacks(stbi_io_callbacks const *clbk, void *user, int *x, int *y, int *comp); +STBIDEF int stbi_is_16_bit_from_memory(stbi_uc const *buffer, int len); +STBIDEF int stbi_is_16_bit_from_callbacks(stbi_io_callbacks const *clbk, void *user); + +#ifndef STBI_NO_STDIO +STBIDEF int stbi_info (char const *filename, int *x, int *y, int *comp); +STBIDEF int stbi_info_from_file (FILE *f, int *x, int *y, int *comp); +STBIDEF int stbi_is_16_bit (char const *filename); +STBIDEF int stbi_is_16_bit_from_file(FILE *f); +#endif + + + +// for image formats that explicitly notate that they have premultiplied alpha, +// we just return the colors as stored in the file. set this flag to force +// unpremultiplication. results are undefined if the unpremultiply overflow. +STBIDEF void stbi_set_unpremultiply_on_load(int flag_true_if_should_unpremultiply); + +// indicate whether we should process iphone images back to canonical format, +// or just pass them through "as-is" +STBIDEF void stbi_convert_iphone_png_to_rgb(int flag_true_if_should_convert); + +// flip the image vertically, so the first pixel in the output array is the bottom left +STBIDEF void stbi_set_flip_vertically_on_load(int flag_true_if_should_flip); + +// as above, but only applies to images loaded on the thread that calls the function +// this function is only available if your compiler supports thread-local variables; +// calling it will fail to link if your compiler doesn't +STBIDEF void stbi_set_flip_vertically_on_load_thread(int flag_true_if_should_flip); + +// ZLIB client - used by PNG, available for other purposes + +STBIDEF char *stbi_zlib_decode_malloc_guesssize(const char *buffer, int len, int initial_size, int *outlen); +STBIDEF char *stbi_zlib_decode_malloc_guesssize_headerflag(const char *buffer, int len, int initial_size, int *outlen, int parse_header); +STBIDEF char *stbi_zlib_decode_malloc(const char *buffer, int len, int *outlen); +STBIDEF int stbi_zlib_decode_buffer(char *obuffer, int olen, const char *ibuffer, int ilen); + +STBIDEF char *stbi_zlib_decode_noheader_malloc(const char *buffer, int len, int *outlen); +STBIDEF int stbi_zlib_decode_noheader_buffer(char *obuffer, int olen, const char *ibuffer, int ilen); + + +#ifdef __cplusplus +} +#endif + +// +// +//// end header file ///////////////////////////////////////////////////// +#endif // STBI_INCLUDE_STB_IMAGE_H + +#ifdef STB_IMAGE_IMPLEMENTATION + +#if defined(STBI_ONLY_JPEG) || defined(STBI_ONLY_PNG) || defined(STBI_ONLY_BMP) \ + || defined(STBI_ONLY_TGA) || defined(STBI_ONLY_GIF) || defined(STBI_ONLY_PSD) \ + || defined(STBI_ONLY_HDR) || defined(STBI_ONLY_PIC) || defined(STBI_ONLY_PNM) \ + || defined(STBI_ONLY_ZLIB) + #ifndef STBI_ONLY_JPEG + #define STBI_NO_JPEG + #endif + #ifndef STBI_ONLY_PNG + #define STBI_NO_PNG + #endif + #ifndef STBI_ONLY_BMP + #define STBI_NO_BMP + #endif + #ifndef STBI_ONLY_PSD + #define STBI_NO_PSD + #endif + #ifndef STBI_ONLY_TGA + #define STBI_NO_TGA + #endif + #ifndef STBI_ONLY_GIF + #define STBI_NO_GIF + #endif + #ifndef STBI_ONLY_HDR + #define STBI_NO_HDR + #endif + #ifndef STBI_ONLY_PIC + #define STBI_NO_PIC + #endif + #ifndef STBI_ONLY_PNM + #define STBI_NO_PNM + #endif +#endif + +#if defined(STBI_NO_PNG) && !defined(STBI_SUPPORT_ZLIB) && !defined(STBI_NO_ZLIB) +#define STBI_NO_ZLIB +#endif + + +#include +#include // ptrdiff_t on osx +#include +#include +#include + +#if !defined(STBI_NO_LINEAR) || !defined(STBI_NO_HDR) +#include // ldexp, pow +#endif + +#ifndef STBI_NO_STDIO +#include +#endif + +#ifndef STBI_ASSERT +#include +#define STBI_ASSERT(x) assert(x) +#endif + +#ifdef __cplusplus +#define STBI_EXTERN extern "C" +#else +#define STBI_EXTERN extern +#endif + + +#ifndef _MSC_VER + #ifdef __cplusplus + #define stbi_inline inline + #else + #define stbi_inline + #endif +#else + #define stbi_inline __forceinline +#endif + +#ifndef STBI_NO_THREAD_LOCALS + #if defined(__cplusplus) && __cplusplus >= 201103L + #define STBI_THREAD_LOCAL thread_local + #elif defined (__STDC_VERSION__) && __STDC_VERSION__ >= 201112L + #define STBI_THREAD_LOCAL _Thread_local + #elif defined(__GNUC__) + #define STBI_THREAD_LOCAL __thread + #elif defined(_MSC_VER) + #define STBI_THREAD_LOCAL __declspec(thread) +#endif +#endif + +#ifdef _MSC_VER +typedef unsigned short stbi__uint16; +typedef signed short stbi__int16; +typedef unsigned int stbi__uint32; +typedef signed int stbi__int32; +#else +#include +typedef uint16_t stbi__uint16; +typedef int16_t stbi__int16; +typedef uint32_t stbi__uint32; +typedef int32_t stbi__int32; +#endif + +// should produce compiler error if size is wrong +typedef unsigned char validate_uint32[sizeof(stbi__uint32)==4 ? 1 : -1]; + +#ifdef _MSC_VER +#define STBI_NOTUSED(v) (void)(v) +#else +#define STBI_NOTUSED(v) (void)(v) +#endif + +#ifdef _MSC_VER +#define STBI_HAS_LROTL +#endif + +#ifdef STBI_HAS_LROTL + #define stbi_lrot(x,y) _lrotl(x,y) +#else + #define stbi_lrot(x,y) (((x) << (y)) | ((x) >> (32 - (y)))) +#endif + +#if defined(STBI_MALLOC) && defined(STBI_FREE) && (defined(STBI_REALLOC) || defined(STBI_REALLOC_SIZED)) +// ok +#elif !defined(STBI_MALLOC) && !defined(STBI_FREE) && !defined(STBI_REALLOC) && !defined(STBI_REALLOC_SIZED) +// ok +#else +#error "Must define all or none of STBI_MALLOC, STBI_FREE, and STBI_REALLOC (or STBI_REALLOC_SIZED)." +#endif + +#ifndef STBI_MALLOC +#define STBI_MALLOC(sz) malloc(sz) +#define STBI_REALLOC(p,newsz) realloc(p,newsz) +#define STBI_FREE(p) free(p) +#endif + +#ifndef STBI_REALLOC_SIZED +#define STBI_REALLOC_SIZED(p,oldsz,newsz) STBI_REALLOC(p,newsz) +#endif + +// x86/x64 detection +#if defined(__x86_64__) || defined(_M_X64) +#define STBI__X64_TARGET +#elif defined(__i386) || defined(_M_IX86) +#define STBI__X86_TARGET +#endif + +#if defined(__GNUC__) && defined(STBI__X86_TARGET) && !defined(__SSE2__) && !defined(STBI_NO_SIMD) +// gcc doesn't support sse2 intrinsics unless you compile with -msse2, +// which in turn means it gets to use SSE2 everywhere. This is unfortunate, +// but previous attempts to provide the SSE2 functions with runtime +// detection caused numerous issues. The way architecture extensions are +// exposed in GCC/Clang is, sadly, not really suited for one-file libs. +// New behavior: if compiled with -msse2, we use SSE2 without any +// detection; if not, we don't use it at all. +#define STBI_NO_SIMD +#endif + +#if defined(__MINGW32__) && defined(STBI__X86_TARGET) && !defined(STBI_MINGW_ENABLE_SSE2) && !defined(STBI_NO_SIMD) +// Note that __MINGW32__ doesn't actually mean 32-bit, so we have to avoid STBI__X64_TARGET +// +// 32-bit MinGW wants ESP to be 16-byte aligned, but this is not in the +// Windows ABI and VC++ as well as Windows DLLs don't maintain that invariant. +// As a result, enabling SSE2 on 32-bit MinGW is dangerous when not +// simultaneously enabling "-mstackrealign". +// +// See https://github.com/nothings/stb/issues/81 for more information. +// +// So default to no SSE2 on 32-bit MinGW. If you've read this far and added +// -mstackrealign to your build settings, feel free to #define STBI_MINGW_ENABLE_SSE2. +#define STBI_NO_SIMD +#endif + +#if !defined(STBI_NO_SIMD) && (defined(STBI__X86_TARGET) || defined(STBI__X64_TARGET)) +#define STBI_SSE2 +#include + +#ifdef _MSC_VER + +#if _MSC_VER >= 1400 // not VC6 +#include // __cpuid +static int stbi__cpuid3(void) +{ + int info[4]; + __cpuid(info,1); + return info[3]; +} +#else +static int stbi__cpuid3(void) +{ + int res; + __asm { + mov eax,1 + cpuid + mov res,edx + } + return res; +} +#endif + +#define STBI_SIMD_ALIGN(type, name) __declspec(align(16)) type name + +#if !defined(STBI_NO_JPEG) && defined(STBI_SSE2) +static int stbi__sse2_available(void) +{ + int info3 = stbi__cpuid3(); + return ((info3 >> 26) & 1) != 0; +} +#endif + +#else // assume GCC-style if not VC++ +#define STBI_SIMD_ALIGN(type, name) type name __attribute__((aligned(16))) + +#if !defined(STBI_NO_JPEG) && defined(STBI_SSE2) +static int stbi__sse2_available(void) +{ + // If we're even attempting to compile this on GCC/Clang, that means + // -msse2 is on, which means the compiler is allowed to use SSE2 + // instructions at will, and so are we. + return 1; +} +#endif + +#endif +#endif + +// ARM NEON +#if defined(STBI_NO_SIMD) && defined(STBI_NEON) +#undef STBI_NEON +#endif + +#ifdef STBI_NEON +#include +// assume GCC or Clang on ARM targets +#define STBI_SIMD_ALIGN(type, name) type name __attribute__((aligned(16))) +#endif + +#ifndef STBI_SIMD_ALIGN +#define STBI_SIMD_ALIGN(type, name) type name +#endif + +/////////////////////////////////////////////// +// +// stbi__context struct and start_xxx functions + +// stbi__context structure is our basic context used by all images, so it +// contains all the IO context, plus some basic image information +typedef struct +{ + stbi__uint32 img_x, img_y; + int img_n, img_out_n; + + stbi_io_callbacks io; + void *io_user_data; + + int read_from_callbacks; + int buflen; + stbi_uc buffer_start[128]; + + stbi_uc *img_buffer, *img_buffer_end; + stbi_uc *img_buffer_original, *img_buffer_original_end; +} stbi__context; + + +static void stbi__refill_buffer(stbi__context *s); + +// initialize a memory-decode context +static void stbi__start_mem(stbi__context *s, stbi_uc const *buffer, int len) +{ + s->io.read = NULL; + s->read_from_callbacks = 0; + s->img_buffer = s->img_buffer_original = (stbi_uc *) buffer; + s->img_buffer_end = s->img_buffer_original_end = (stbi_uc *) buffer+len; +} + +// initialize a callback-based context +static void stbi__start_callbacks(stbi__context *s, stbi_io_callbacks *c, void *user) +{ + s->io = *c; + s->io_user_data = user; + s->buflen = sizeof(s->buffer_start); + s->read_from_callbacks = 1; + s->img_buffer_original = s->buffer_start; + stbi__refill_buffer(s); + s->img_buffer_original_end = s->img_buffer_end; +} + +#ifndef STBI_NO_STDIO + +static int stbi__stdio_read(void *user, char *data, int size) +{ + return (int) fread(data,1,size,(FILE*) user); +} + +static void stbi__stdio_skip(void *user, int n) +{ + fseek((FILE*) user, n, SEEK_CUR); +} + +static int stbi__stdio_eof(void *user) +{ + return feof((FILE*) user); +} + +static stbi_io_callbacks stbi__stdio_callbacks = +{ + stbi__stdio_read, + stbi__stdio_skip, + stbi__stdio_eof, +}; + +static void stbi__start_file(stbi__context *s, FILE *f) +{ + stbi__start_callbacks(s, &stbi__stdio_callbacks, (void *) f); +} + +//static void stop_file(stbi__context *s) { } + +#endif // !STBI_NO_STDIO + +static void stbi__rewind(stbi__context *s) +{ + // conceptually rewind SHOULD rewind to the beginning of the stream, + // but we just rewind to the beginning of the initial buffer, because + // we only use it after doing 'test', which only ever looks at at most 92 bytes + s->img_buffer = s->img_buffer_original; + s->img_buffer_end = s->img_buffer_original_end; +} + +enum +{ + STBI_ORDER_RGB, + STBI_ORDER_BGR +}; + +typedef struct +{ + int bits_per_channel; + int num_channels; + int channel_order; +} stbi__result_info; + +#ifndef STBI_NO_JPEG +static int stbi__jpeg_test(stbi__context *s); +static void *stbi__jpeg_load(stbi__context *s, int *x, int *y, int *comp, int req_comp, stbi__result_info *ri); +static int stbi__jpeg_info(stbi__context *s, int *x, int *y, int *comp); +#endif + +#ifndef STBI_NO_PNG +static int stbi__png_test(stbi__context *s); +static void *stbi__png_load(stbi__context *s, int *x, int *y, int *comp, int req_comp, stbi__result_info *ri); +static int stbi__png_info(stbi__context *s, int *x, int *y, int *comp); +static int stbi__png_is16(stbi__context *s); +#endif + +#ifndef STBI_NO_BMP +static int stbi__bmp_test(stbi__context *s); +static void *stbi__bmp_load(stbi__context *s, int *x, int *y, int *comp, int req_comp, stbi__result_info *ri); +static int stbi__bmp_info(stbi__context *s, int *x, int *y, int *comp); +#endif + +#ifndef STBI_NO_TGA +static int stbi__tga_test(stbi__context *s); +static void *stbi__tga_load(stbi__context *s, int *x, int *y, int *comp, int req_comp, stbi__result_info *ri); +static int stbi__tga_info(stbi__context *s, int *x, int *y, int *comp); +#endif + +#ifndef STBI_NO_PSD +static int stbi__psd_test(stbi__context *s); +static void *stbi__psd_load(stbi__context *s, int *x, int *y, int *comp, int req_comp, stbi__result_info *ri, int bpc); +static int stbi__psd_info(stbi__context *s, int *x, int *y, int *comp); +static int stbi__psd_is16(stbi__context *s); +#endif + +#ifndef STBI_NO_HDR +static int stbi__hdr_test(stbi__context *s); +static float *stbi__hdr_load(stbi__context *s, int *x, int *y, int *comp, int req_comp, stbi__result_info *ri); +static int stbi__hdr_info(stbi__context *s, int *x, int *y, int *comp); +#endif + +#ifndef STBI_NO_PIC +static int stbi__pic_test(stbi__context *s); +static void *stbi__pic_load(stbi__context *s, int *x, int *y, int *comp, int req_comp, stbi__result_info *ri); +static int stbi__pic_info(stbi__context *s, int *x, int *y, int *comp); +#endif + +#ifndef STBI_NO_GIF +static int stbi__gif_test(stbi__context *s); +static void *stbi__gif_load(stbi__context *s, int *x, int *y, int *comp, int req_comp, stbi__result_info *ri); +static void *stbi__load_gif_main(stbi__context *s, int **delays, int *x, int *y, int *z, int *comp, int req_comp); +static int stbi__gif_info(stbi__context *s, int *x, int *y, int *comp); +#endif + +#ifndef STBI_NO_PNM +static int stbi__pnm_test(stbi__context *s); +static void *stbi__pnm_load(stbi__context *s, int *x, int *y, int *comp, int req_comp, stbi__result_info *ri); +static int stbi__pnm_info(stbi__context *s, int *x, int *y, int *comp); +#endif + +static +#ifdef STBI_THREAD_LOCAL +STBI_THREAD_LOCAL +#endif +const char *stbi__g_failure_reason; + +STBIDEF const char *stbi_failure_reason(void) +{ + return stbi__g_failure_reason; +} + +#ifndef STBI_NO_FAILURE_STRINGS +static int stbi__err(const char *str) +{ + stbi__g_failure_reason = str; + return 0; +} +#endif + +static void *stbi__malloc(size_t size) +{ + return STBI_MALLOC(size); +} + +// stb_image uses ints pervasively, including for offset calculations. +// therefore the largest decoded image size we can support with the +// current code, even on 64-bit targets, is INT_MAX. this is not a +// significant limitation for the intended use case. +// +// we do, however, need to make sure our size calculations don't +// overflow. hence a few helper functions for size calculations that +// multiply integers together, making sure that they're non-negative +// and no overflow occurs. + +// return 1 if the sum is valid, 0 on overflow. +// negative terms are considered invalid. +static int stbi__addsizes_valid(int a, int b) +{ + if (b < 0) return 0; + // now 0 <= b <= INT_MAX, hence also + // 0 <= INT_MAX - b <= INTMAX. + // And "a + b <= INT_MAX" (which might overflow) is the + // same as a <= INT_MAX - b (no overflow) + return a <= INT_MAX - b; +} + +// returns 1 if the product is valid, 0 on overflow. +// negative factors are considered invalid. +static int stbi__mul2sizes_valid(int a, int b) +{ + if (a < 0 || b < 0) return 0; + if (b == 0) return 1; // mul-by-0 is always safe + // portable way to check for no overflows in a*b + return a <= INT_MAX/b; +} + +#if !defined(STBI_NO_JPEG) || !defined(STBI_NO_PNG) || !defined(STBI_NO_TGA) || !defined(STBI_NO_HDR) +// returns 1 if "a*b + add" has no negative terms/factors and doesn't overflow +static int stbi__mad2sizes_valid(int a, int b, int add) +{ + return stbi__mul2sizes_valid(a, b) && stbi__addsizes_valid(a*b, add); +} +#endif + +// returns 1 if "a*b*c + add" has no negative terms/factors and doesn't overflow +static int stbi__mad3sizes_valid(int a, int b, int c, int add) +{ + return stbi__mul2sizes_valid(a, b) && stbi__mul2sizes_valid(a*b, c) && + stbi__addsizes_valid(a*b*c, add); +} + +// returns 1 if "a*b*c*d + add" has no negative terms/factors and doesn't overflow +#if !defined(STBI_NO_LINEAR) || !defined(STBI_NO_HDR) +static int stbi__mad4sizes_valid(int a, int b, int c, int d, int add) +{ + return stbi__mul2sizes_valid(a, b) && stbi__mul2sizes_valid(a*b, c) && + stbi__mul2sizes_valid(a*b*c, d) && stbi__addsizes_valid(a*b*c*d, add); +} +#endif + +#if !defined(STBI_NO_JPEG) || !defined(STBI_NO_PNG) || !defined(STBI_NO_TGA) || !defined(STBI_NO_HDR) +// mallocs with size overflow checking +static void *stbi__malloc_mad2(int a, int b, int add) +{ + if (!stbi__mad2sizes_valid(a, b, add)) return NULL; + return stbi__malloc(a*b + add); +} +#endif + +static void *stbi__malloc_mad3(int a, int b, int c, int add) +{ + if (!stbi__mad3sizes_valid(a, b, c, add)) return NULL; + return stbi__malloc(a*b*c + add); +} + +#if !defined(STBI_NO_LINEAR) || !defined(STBI_NO_HDR) +static void *stbi__malloc_mad4(int a, int b, int c, int d, int add) +{ + if (!stbi__mad4sizes_valid(a, b, c, d, add)) return NULL; + return stbi__malloc(a*b*c*d + add); +} +#endif + +// stbi__err - error +// stbi__errpf - error returning pointer to float +// stbi__errpuc - error returning pointer to unsigned char + +#ifdef STBI_NO_FAILURE_STRINGS + #define stbi__err(x,y) 0 +#elif defined(STBI_FAILURE_USERMSG) + #define stbi__err(x,y) stbi__err(y) +#else + #define stbi__err(x,y) stbi__err(x) +#endif + +#define stbi__errpf(x,y) ((float *)(size_t) (stbi__err(x,y)?NULL:NULL)) +#define stbi__errpuc(x,y) ((unsigned char *)(size_t) (stbi__err(x,y)?NULL:NULL)) + +STBIDEF void stbi_image_free(void *retval_from_stbi_load) +{ + STBI_FREE(retval_from_stbi_load); +} + +#ifndef STBI_NO_LINEAR +static float *stbi__ldr_to_hdr(stbi_uc *data, int x, int y, int comp); +#endif + +#ifndef STBI_NO_HDR +static stbi_uc *stbi__hdr_to_ldr(float *data, int x, int y, int comp); +#endif + +static int stbi__vertically_flip_on_load_global = 0; + +STBIDEF void stbi_set_flip_vertically_on_load(int flag_true_if_should_flip) +{ + stbi__vertically_flip_on_load_global = flag_true_if_should_flip; +} + +#ifndef STBI_THREAD_LOCAL +#define stbi__vertically_flip_on_load stbi__vertically_flip_on_load_global +#else +static STBI_THREAD_LOCAL int stbi__vertically_flip_on_load_local, stbi__vertically_flip_on_load_set; + +STBIDEF void stbi_set_flip_vertically_on_load_thread(int flag_true_if_should_flip) +{ + stbi__vertically_flip_on_load_local = flag_true_if_should_flip; + stbi__vertically_flip_on_load_set = 1; +} + +#define stbi__vertically_flip_on_load (stbi__vertically_flip_on_load_set \ + ? stbi__vertically_flip_on_load_local \ + : stbi__vertically_flip_on_load_global) +#endif // STBI_THREAD_LOCAL + +static void *stbi__load_main(stbi__context *s, int *x, int *y, int *comp, int req_comp, stbi__result_info *ri, int bpc) +{ + memset(ri, 0, sizeof(*ri)); // make sure it's initialized if we add new fields + ri->bits_per_channel = 8; // default is 8 so most paths don't have to be changed + ri->channel_order = STBI_ORDER_RGB; // all current input & output are this, but this is here so we can add BGR order + ri->num_channels = 0; + + #ifndef STBI_NO_JPEG + if (stbi__jpeg_test(s)) return stbi__jpeg_load(s,x,y,comp,req_comp, ri); + #endif + #ifndef STBI_NO_PNG + if (stbi__png_test(s)) return stbi__png_load(s,x,y,comp,req_comp, ri); + #endif + #ifndef STBI_NO_BMP + if (stbi__bmp_test(s)) return stbi__bmp_load(s,x,y,comp,req_comp, ri); + #endif + #ifndef STBI_NO_GIF + if (stbi__gif_test(s)) return stbi__gif_load(s,x,y,comp,req_comp, ri); + #endif + #ifndef STBI_NO_PSD + if (stbi__psd_test(s)) return stbi__psd_load(s,x,y,comp,req_comp, ri, bpc); + #else + STBI_NOTUSED(bpc); + #endif + #ifndef STBI_NO_PIC + if (stbi__pic_test(s)) return stbi__pic_load(s,x,y,comp,req_comp, ri); + #endif + #ifndef STBI_NO_PNM + if (stbi__pnm_test(s)) return stbi__pnm_load(s,x,y,comp,req_comp, ri); + #endif + + #ifndef STBI_NO_HDR + if (stbi__hdr_test(s)) { + float *hdr = stbi__hdr_load(s, x,y,comp,req_comp, ri); + return stbi__hdr_to_ldr(hdr, *x, *y, req_comp ? req_comp : *comp); + } + #endif + + #ifndef STBI_NO_TGA + // test tga last because it's a crappy test! + if (stbi__tga_test(s)) + return stbi__tga_load(s,x,y,comp,req_comp, ri); + #endif + + return stbi__errpuc("unknown image type", "Image not of any known type, or corrupt"); +} + +static stbi_uc *stbi__convert_16_to_8(stbi__uint16 *orig, int w, int h, int channels) +{ + int i; + int img_len = w * h * channels; + stbi_uc *reduced; + + reduced = (stbi_uc *) stbi__malloc(img_len); + if (reduced == NULL) return stbi__errpuc("outofmem", "Out of memory"); + + for (i = 0; i < img_len; ++i) + reduced[i] = (stbi_uc)((orig[i] >> 8) & 0xFF); // top half of each byte is sufficient approx of 16->8 bit scaling + + STBI_FREE(orig); + return reduced; +} + +static stbi__uint16 *stbi__convert_8_to_16(stbi_uc *orig, int w, int h, int channels) +{ + int i; + int img_len = w * h * channels; + stbi__uint16 *enlarged; + + enlarged = (stbi__uint16 *) stbi__malloc(img_len*2); + if (enlarged == NULL) return (stbi__uint16 *) stbi__errpuc("outofmem", "Out of memory"); + + for (i = 0; i < img_len; ++i) + enlarged[i] = (stbi__uint16)((orig[i] << 8) + orig[i]); // replicate to high and low byte, maps 0->0, 255->0xffff + + STBI_FREE(orig); + return enlarged; +} + +static void stbi__vertical_flip(void *image, int w, int h, int bytes_per_pixel) +{ + int row; + size_t bytes_per_row = (size_t)w * bytes_per_pixel; + stbi_uc temp[2048]; + stbi_uc *bytes = (stbi_uc *)image; + + for (row = 0; row < (h>>1); row++) { + stbi_uc *row0 = bytes + row*bytes_per_row; + stbi_uc *row1 = bytes + (h - row - 1)*bytes_per_row; + // swap row0 with row1 + size_t bytes_left = bytes_per_row; + while (bytes_left) { + size_t bytes_copy = (bytes_left < sizeof(temp)) ? bytes_left : sizeof(temp); + memcpy(temp, row0, bytes_copy); + memcpy(row0, row1, bytes_copy); + memcpy(row1, temp, bytes_copy); + row0 += bytes_copy; + row1 += bytes_copy; + bytes_left -= bytes_copy; + } + } +} + +#ifndef STBI_NO_GIF +static void stbi__vertical_flip_slices(void *image, int w, int h, int z, int bytes_per_pixel) +{ + int slice; + int slice_size = w * h * bytes_per_pixel; + + stbi_uc *bytes = (stbi_uc *)image; + for (slice = 0; slice < z; ++slice) { + stbi__vertical_flip(bytes, w, h, bytes_per_pixel); + bytes += slice_size; + } +} +#endif + +static unsigned char *stbi__load_and_postprocess_8bit(stbi__context *s, int *x, int *y, int *comp, int req_comp) +{ + stbi__result_info ri; + void *result = stbi__load_main(s, x, y, comp, req_comp, &ri, 8); + + if (result == NULL) + return NULL; + + if (ri.bits_per_channel != 8) { + STBI_ASSERT(ri.bits_per_channel == 16); + result = stbi__convert_16_to_8((stbi__uint16 *) result, *x, *y, req_comp == 0 ? *comp : req_comp); + ri.bits_per_channel = 8; + } + + // @TODO: move stbi__convert_format to here + + if (stbi__vertically_flip_on_load) { + int channels = req_comp ? req_comp : *comp; + stbi__vertical_flip(result, *x, *y, channels * sizeof(stbi_uc)); + } + + return (unsigned char *) result; +} + +static stbi__uint16 *stbi__load_and_postprocess_16bit(stbi__context *s, int *x, int *y, int *comp, int req_comp) +{ + stbi__result_info ri; + void *result = stbi__load_main(s, x, y, comp, req_comp, &ri, 16); + + if (result == NULL) + return NULL; + + if (ri.bits_per_channel != 16) { + STBI_ASSERT(ri.bits_per_channel == 8); + result = stbi__convert_8_to_16((stbi_uc *) result, *x, *y, req_comp == 0 ? *comp : req_comp); + ri.bits_per_channel = 16; + } + + // @TODO: move stbi__convert_format16 to here + // @TODO: special case RGB-to-Y (and RGBA-to-YA) for 8-bit-to-16-bit case to keep more precision + + if (stbi__vertically_flip_on_load) { + int channels = req_comp ? req_comp : *comp; + stbi__vertical_flip(result, *x, *y, channels * sizeof(stbi__uint16)); + } + + return (stbi__uint16 *) result; +} + +#if !defined(STBI_NO_HDR) && !defined(STBI_NO_LINEAR) +static void stbi__float_postprocess(float *result, int *x, int *y, int *comp, int req_comp) +{ + if (stbi__vertically_flip_on_load && result != NULL) { + int channels = req_comp ? req_comp : *comp; + stbi__vertical_flip(result, *x, *y, channels * sizeof(float)); + } +} +#endif + +#ifndef STBI_NO_STDIO + +#if defined(_MSC_VER) && defined(STBI_WINDOWS_UTF8) +STBI_EXTERN __declspec(dllimport) int __stdcall MultiByteToWideChar(unsigned int cp, unsigned long flags, const char *str, int cbmb, wchar_t *widestr, int cchwide); +STBI_EXTERN __declspec(dllimport) int __stdcall WideCharToMultiByte(unsigned int cp, unsigned long flags, const wchar_t *widestr, int cchwide, char *str, int cbmb, const char *defchar, int *used_default); +#endif + +#if defined(_MSC_VER) && defined(STBI_WINDOWS_UTF8) +STBIDEF int stbi_convert_wchar_to_utf8(char *buffer, size_t bufferlen, const wchar_t* input) +{ + return WideCharToMultiByte(65001 /* UTF8 */, 0, input, -1, buffer, (int) bufferlen, NULL, NULL); +} +#endif + +static FILE *stbi__fopen(char const *filename, char const *mode) +{ + FILE *f; +#if defined(_MSC_VER) && defined(STBI_WINDOWS_UTF8) + wchar_t wMode[64]; + wchar_t wFilename[1024]; + if (0 == MultiByteToWideChar(65001 /* UTF8 */, 0, filename, -1, wFilename, sizeof(wFilename))) + return 0; + + if (0 == MultiByteToWideChar(65001 /* UTF8 */, 0, mode, -1, wMode, sizeof(wMode))) + return 0; + +#if _MSC_VER >= 1400 + if (0 != _wfopen_s(&f, wFilename, wMode)) + f = 0; +#else + f = _wfopen(wFilename, wMode); +#endif + +#elif defined(_MSC_VER) && _MSC_VER >= 1400 + if (0 != fopen_s(&f, filename, mode)) + f=0; +#else + f = fopen(filename, mode); +#endif + return f; +} + + +STBIDEF stbi_uc *stbi_load(char const *filename, int *x, int *y, int *comp, int req_comp) +{ + FILE *f = stbi__fopen(filename, "rb"); + unsigned char *result; + if (!f) return stbi__errpuc("can't fopen", "Unable to open file"); + result = stbi_load_from_file(f,x,y,comp,req_comp); + fclose(f); + return result; +} + +STBIDEF stbi_uc *stbi_load_from_file(FILE *f, int *x, int *y, int *comp, int req_comp) +{ + unsigned char *result; + stbi__context s; + stbi__start_file(&s,f); + result = stbi__load_and_postprocess_8bit(&s,x,y,comp,req_comp); + if (result) { + // need to 'unget' all the characters in the IO buffer + fseek(f, - (int) (s.img_buffer_end - s.img_buffer), SEEK_CUR); + } + return result; +} + +STBIDEF stbi__uint16 *stbi_load_from_file_16(FILE *f, int *x, int *y, int *comp, int req_comp) +{ + stbi__uint16 *result; + stbi__context s; + stbi__start_file(&s,f); + result = stbi__load_and_postprocess_16bit(&s,x,y,comp,req_comp); + if (result) { + // need to 'unget' all the characters in the IO buffer + fseek(f, - (int) (s.img_buffer_end - s.img_buffer), SEEK_CUR); + } + return result; +} + +STBIDEF stbi_us *stbi_load_16(char const *filename, int *x, int *y, int *comp, int req_comp) +{ + FILE *f = stbi__fopen(filename, "rb"); + stbi__uint16 *result; + if (!f) return (stbi_us *) stbi__errpuc("can't fopen", "Unable to open file"); + result = stbi_load_from_file_16(f,x,y,comp,req_comp); + fclose(f); + return result; +} + + +#endif //!STBI_NO_STDIO + +STBIDEF stbi_us *stbi_load_16_from_memory(stbi_uc const *buffer, int len, int *x, int *y, int *channels_in_file, int desired_channels) +{ + stbi__context s; + stbi__start_mem(&s,buffer,len); + return stbi__load_and_postprocess_16bit(&s,x,y,channels_in_file,desired_channels); +} + +STBIDEF stbi_us *stbi_load_16_from_callbacks(stbi_io_callbacks const *clbk, void *user, int *x, int *y, int *channels_in_file, int desired_channels) +{ + stbi__context s; + stbi__start_callbacks(&s, (stbi_io_callbacks *)clbk, user); + return stbi__load_and_postprocess_16bit(&s,x,y,channels_in_file,desired_channels); +} + +STBIDEF stbi_uc *stbi_load_from_memory(stbi_uc const *buffer, int len, int *x, int *y, int *comp, int req_comp) +{ + stbi__context s; + stbi__start_mem(&s,buffer,len); + return stbi__load_and_postprocess_8bit(&s,x,y,comp,req_comp); +} + +STBIDEF stbi_uc *stbi_load_from_callbacks(stbi_io_callbacks const *clbk, void *user, int *x, int *y, int *comp, int req_comp) +{ + stbi__context s; + stbi__start_callbacks(&s, (stbi_io_callbacks *) clbk, user); + return stbi__load_and_postprocess_8bit(&s,x,y,comp,req_comp); +} + +#ifndef STBI_NO_GIF +STBIDEF stbi_uc *stbi_load_gif_from_memory(stbi_uc const *buffer, int len, int **delays, int *x, int *y, int *z, int *comp, int req_comp) +{ + unsigned char *result; + stbi__context s; + stbi__start_mem(&s,buffer,len); + + result = (unsigned char*) stbi__load_gif_main(&s, delays, x, y, z, comp, req_comp); + if (stbi__vertically_flip_on_load) { + stbi__vertical_flip_slices( result, *x, *y, *z, *comp ); + } + + return result; +} +#endif + +#ifndef STBI_NO_LINEAR +static float *stbi__loadf_main(stbi__context *s, int *x, int *y, int *comp, int req_comp) +{ + unsigned char *data; + #ifndef STBI_NO_HDR + if (stbi__hdr_test(s)) { + stbi__result_info ri; + float *hdr_data = stbi__hdr_load(s,x,y,comp,req_comp, &ri); + if (hdr_data) + stbi__float_postprocess(hdr_data,x,y,comp,req_comp); + return hdr_data; + } + #endif + data = stbi__load_and_postprocess_8bit(s, x, y, comp, req_comp); + if (data) + return stbi__ldr_to_hdr(data, *x, *y, req_comp ? req_comp : *comp); + return stbi__errpf("unknown image type", "Image not of any known type, or corrupt"); +} + +STBIDEF float *stbi_loadf_from_memory(stbi_uc const *buffer, int len, int *x, int *y, int *comp, int req_comp) +{ + stbi__context s; + stbi__start_mem(&s,buffer,len); + return stbi__loadf_main(&s,x,y,comp,req_comp); +} + +STBIDEF float *stbi_loadf_from_callbacks(stbi_io_callbacks const *clbk, void *user, int *x, int *y, int *comp, int req_comp) +{ + stbi__context s; + stbi__start_callbacks(&s, (stbi_io_callbacks *) clbk, user); + return stbi__loadf_main(&s,x,y,comp,req_comp); +} + +#ifndef STBI_NO_STDIO +STBIDEF float *stbi_loadf(char const *filename, int *x, int *y, int *comp, int req_comp) +{ + float *result; + FILE *f = stbi__fopen(filename, "rb"); + if (!f) return stbi__errpf("can't fopen", "Unable to open file"); + result = stbi_loadf_from_file(f,x,y,comp,req_comp); + fclose(f); + return result; +} + +STBIDEF float *stbi_loadf_from_file(FILE *f, int *x, int *y, int *comp, int req_comp) +{ + stbi__context s; + stbi__start_file(&s,f); + return stbi__loadf_main(&s,x,y,comp,req_comp); +} +#endif // !STBI_NO_STDIO + +#endif // !STBI_NO_LINEAR + +// these is-hdr-or-not is defined independent of whether STBI_NO_LINEAR is +// defined, for API simplicity; if STBI_NO_LINEAR is defined, it always +// reports false! + +STBIDEF int stbi_is_hdr_from_memory(stbi_uc const *buffer, int len) +{ + #ifndef STBI_NO_HDR + stbi__context s; + stbi__start_mem(&s,buffer,len); + return stbi__hdr_test(&s); + #else + STBI_NOTUSED(buffer); + STBI_NOTUSED(len); + return 0; + #endif +} + +#ifndef STBI_NO_STDIO +STBIDEF int stbi_is_hdr (char const *filename) +{ + FILE *f = stbi__fopen(filename, "rb"); + int result=0; + if (f) { + result = stbi_is_hdr_from_file(f); + fclose(f); + } + return result; +} + +STBIDEF int stbi_is_hdr_from_file(FILE *f) +{ + #ifndef STBI_NO_HDR + long pos = ftell(f); + int res; + stbi__context s; + stbi__start_file(&s,f); + res = stbi__hdr_test(&s); + fseek(f, pos, SEEK_SET); + return res; + #else + STBI_NOTUSED(f); + return 0; + #endif +} +#endif // !STBI_NO_STDIO + +STBIDEF int stbi_is_hdr_from_callbacks(stbi_io_callbacks const *clbk, void *user) +{ + #ifndef STBI_NO_HDR + stbi__context s; + stbi__start_callbacks(&s, (stbi_io_callbacks *) clbk, user); + return stbi__hdr_test(&s); + #else + STBI_NOTUSED(clbk); + STBI_NOTUSED(user); + return 0; + #endif +} + +#ifndef STBI_NO_LINEAR +static float stbi__l2h_gamma=2.2f, stbi__l2h_scale=1.0f; + +STBIDEF void stbi_ldr_to_hdr_gamma(float gamma) { stbi__l2h_gamma = gamma; } +STBIDEF void stbi_ldr_to_hdr_scale(float scale) { stbi__l2h_scale = scale; } +#endif + +static float stbi__h2l_gamma_i=1.0f/2.2f, stbi__h2l_scale_i=1.0f; + +STBIDEF void stbi_hdr_to_ldr_gamma(float gamma) { stbi__h2l_gamma_i = 1/gamma; } +STBIDEF void stbi_hdr_to_ldr_scale(float scale) { stbi__h2l_scale_i = 1/scale; } + + +////////////////////////////////////////////////////////////////////////////// +// +// Common code used by all image loaders +// + +enum +{ + STBI__SCAN_load=0, + STBI__SCAN_type, + STBI__SCAN_header +}; + +static void stbi__refill_buffer(stbi__context *s) +{ + int n = (s->io.read)(s->io_user_data,(char*)s->buffer_start,s->buflen); + if (n == 0) { + // at end of file, treat same as if from memory, but need to handle case + // where s->img_buffer isn't pointing to safe memory, e.g. 0-byte file + s->read_from_callbacks = 0; + s->img_buffer = s->buffer_start; + s->img_buffer_end = s->buffer_start+1; + *s->img_buffer = 0; + } else { + s->img_buffer = s->buffer_start; + s->img_buffer_end = s->buffer_start + n; + } +} + +stbi_inline static stbi_uc stbi__get8(stbi__context *s) +{ + if (s->img_buffer < s->img_buffer_end) + return *s->img_buffer++; + if (s->read_from_callbacks) { + stbi__refill_buffer(s); + return *s->img_buffer++; + } + return 0; +} + +#if defined(STBI_NO_JPEG) && defined(STBI_NO_HDR) && defined(STBI_NO_PIC) && defined(STBI_NO_PNM) +// nothing +#else +stbi_inline static int stbi__at_eof(stbi__context *s) +{ + if (s->io.read) { + if (!(s->io.eof)(s->io_user_data)) return 0; + // if feof() is true, check if buffer = end + // special case: we've only got the special 0 character at the end + if (s->read_from_callbacks == 0) return 1; + } + + return s->img_buffer >= s->img_buffer_end; +} +#endif + +#if defined(STBI_NO_JPEG) && defined(STBI_NO_PNG) && defined(STBI_NO_BMP) && defined(STBI_NO_PSD) && defined(STBI_NO_TGA) && defined(STBI_NO_GIF) && defined(STBI_NO_PIC) +// nothing +#else +static void stbi__skip(stbi__context *s, int n) +{ + if (n < 0) { + s->img_buffer = s->img_buffer_end; + return; + } + if (s->io.read) { + int blen = (int) (s->img_buffer_end - s->img_buffer); + if (blen < n) { + s->img_buffer = s->img_buffer_end; + (s->io.skip)(s->io_user_data, n - blen); + return; + } + } + s->img_buffer += n; +} +#endif + +#if defined(STBI_NO_PNG) && defined(STBI_NO_TGA) && defined(STBI_NO_HDR) && defined(STBI_NO_PNM) +// nothing +#else +static int stbi__getn(stbi__context *s, stbi_uc *buffer, int n) +{ + if (s->io.read) { + int blen = (int) (s->img_buffer_end - s->img_buffer); + if (blen < n) { + int res, count; + + memcpy(buffer, s->img_buffer, blen); + + count = (s->io.read)(s->io_user_data, (char*) buffer + blen, n - blen); + res = (count == (n-blen)); + s->img_buffer = s->img_buffer_end; + return res; + } + } + + if (s->img_buffer+n <= s->img_buffer_end) { + memcpy(buffer, s->img_buffer, n); + s->img_buffer += n; + return 1; + } else + return 0; +} +#endif + +#if defined(STBI_NO_JPEG) && defined(STBI_NO_PNG) && defined(STBI_NO_PSD) && defined(STBI_NO_PIC) +// nothing +#else +static int stbi__get16be(stbi__context *s) +{ + int z = stbi__get8(s); + return (z << 8) + stbi__get8(s); +} +#endif + +#if defined(STBI_NO_PNG) && defined(STBI_NO_PSD) && defined(STBI_NO_PIC) +// nothing +#else +static stbi__uint32 stbi__get32be(stbi__context *s) +{ + stbi__uint32 z = stbi__get16be(s); + return (z << 16) + stbi__get16be(s); +} +#endif + +#if defined(STBI_NO_BMP) && defined(STBI_NO_TGA) && defined(STBI_NO_GIF) +// nothing +#else +static int stbi__get16le(stbi__context *s) +{ + int z = stbi__get8(s); + return z + (stbi__get8(s) << 8); +} +#endif + +#ifndef STBI_NO_BMP +static stbi__uint32 stbi__get32le(stbi__context *s) +{ + stbi__uint32 z = stbi__get16le(s); + return z + (stbi__get16le(s) << 16); +} +#endif + +#define STBI__BYTECAST(x) ((stbi_uc) ((x) & 255)) // truncate int to byte without warnings + +#if defined(STBI_NO_JPEG) && defined(STBI_NO_PNG) && defined(STBI_NO_BMP) && defined(STBI_NO_PSD) && defined(STBI_NO_TGA) && defined(STBI_NO_GIF) && defined(STBI_NO_PIC) && defined(STBI_NO_PNM) +// nothing +#else +////////////////////////////////////////////////////////////////////////////// +// +// generic converter from built-in img_n to req_comp +// individual types do this automatically as much as possible (e.g. jpeg +// does all cases internally since it needs to colorspace convert anyway, +// and it never has alpha, so very few cases ). png can automatically +// interleave an alpha=255 channel, but falls back to this for other cases +// +// assume data buffer is malloced, so malloc a new one and free that one +// only failure mode is malloc failing + +static stbi_uc stbi__compute_y(int r, int g, int b) +{ + return (stbi_uc) (((r*77) + (g*150) + (29*b)) >> 8); +} +#endif + +#if defined(STBI_NO_PNG) && defined(STBI_NO_BMP) && defined(STBI_NO_PSD) && defined(STBI_NO_TGA) && defined(STBI_NO_GIF) && defined(STBI_NO_PIC) && defined(STBI_NO_PNM) +// nothing +#else +static unsigned char *stbi__convert_format(unsigned char *data, int img_n, int req_comp, unsigned int x, unsigned int y) +{ + int i,j; + unsigned char *good; + + if (req_comp == img_n) return data; + STBI_ASSERT(req_comp >= 1 && req_comp <= 4); + + good = (unsigned char *) stbi__malloc_mad3(req_comp, x, y, 0); + if (good == NULL) { + STBI_FREE(data); + return stbi__errpuc("outofmem", "Out of memory"); + } + + for (j=0; j < (int) y; ++j) { + unsigned char *src = data + j * x * img_n ; + unsigned char *dest = good + j * x * req_comp; + + #define STBI__COMBO(a,b) ((a)*8+(b)) + #define STBI__CASE(a,b) case STBI__COMBO(a,b): for(i=x-1; i >= 0; --i, src += a, dest += b) + // convert source image with img_n components to one with req_comp components; + // avoid switch per pixel, so use switch per scanline and massive macros + switch (STBI__COMBO(img_n, req_comp)) { + STBI__CASE(1,2) { dest[0]=src[0]; dest[1]=255; } break; + STBI__CASE(1,3) { dest[0]=dest[1]=dest[2]=src[0]; } break; + STBI__CASE(1,4) { dest[0]=dest[1]=dest[2]=src[0]; dest[3]=255; } break; + STBI__CASE(2,1) { dest[0]=src[0]; } break; + STBI__CASE(2,3) { dest[0]=dest[1]=dest[2]=src[0]; } break; + STBI__CASE(2,4) { dest[0]=dest[1]=dest[2]=src[0]; dest[3]=src[1]; } break; + STBI__CASE(3,4) { dest[0]=src[0];dest[1]=src[1];dest[2]=src[2];dest[3]=255; } break; + STBI__CASE(3,1) { dest[0]=stbi__compute_y(src[0],src[1],src[2]); } break; + STBI__CASE(3,2) { dest[0]=stbi__compute_y(src[0],src[1],src[2]); dest[1] = 255; } break; + STBI__CASE(4,1) { dest[0]=stbi__compute_y(src[0],src[1],src[2]); } break; + STBI__CASE(4,2) { dest[0]=stbi__compute_y(src[0],src[1],src[2]); dest[1] = src[3]; } break; + STBI__CASE(4,3) { dest[0]=src[0];dest[1]=src[1];dest[2]=src[2]; } break; + default: STBI_ASSERT(0); + } + #undef STBI__CASE + } + + STBI_FREE(data); + return good; +} +#endif + +#if defined(STBI_NO_PNG) && defined(STBI_NO_PSD) +// nothing +#else +static stbi__uint16 stbi__compute_y_16(int r, int g, int b) +{ + return (stbi__uint16) (((r*77) + (g*150) + (29*b)) >> 8); +} +#endif + +#if defined(STBI_NO_PNG) && defined(STBI_NO_PSD) +// nothing +#else +static stbi__uint16 *stbi__convert_format16(stbi__uint16 *data, int img_n, int req_comp, unsigned int x, unsigned int y) +{ + int i,j; + stbi__uint16 *good; + + if (req_comp == img_n) return data; + STBI_ASSERT(req_comp >= 1 && req_comp <= 4); + + good = (stbi__uint16 *) stbi__malloc(req_comp * x * y * 2); + if (good == NULL) { + STBI_FREE(data); + return (stbi__uint16 *) stbi__errpuc("outofmem", "Out of memory"); + } + + for (j=0; j < (int) y; ++j) { + stbi__uint16 *src = data + j * x * img_n ; + stbi__uint16 *dest = good + j * x * req_comp; + + #define STBI__COMBO(a,b) ((a)*8+(b)) + #define STBI__CASE(a,b) case STBI__COMBO(a,b): for(i=x-1; i >= 0; --i, src += a, dest += b) + // convert source image with img_n components to one with req_comp components; + // avoid switch per pixel, so use switch per scanline and massive macros + switch (STBI__COMBO(img_n, req_comp)) { + STBI__CASE(1,2) { dest[0]=src[0]; dest[1]=0xffff; } break; + STBI__CASE(1,3) { dest[0]=dest[1]=dest[2]=src[0]; } break; + STBI__CASE(1,4) { dest[0]=dest[1]=dest[2]=src[0]; dest[3]=0xffff; } break; + STBI__CASE(2,1) { dest[0]=src[0]; } break; + STBI__CASE(2,3) { dest[0]=dest[1]=dest[2]=src[0]; } break; + STBI__CASE(2,4) { dest[0]=dest[1]=dest[2]=src[0]; dest[3]=src[1]; } break; + STBI__CASE(3,4) { dest[0]=src[0];dest[1]=src[1];dest[2]=src[2];dest[3]=0xffff; } break; + STBI__CASE(3,1) { dest[0]=stbi__compute_y_16(src[0],src[1],src[2]); } break; + STBI__CASE(3,2) { dest[0]=stbi__compute_y_16(src[0],src[1],src[2]); dest[1] = 0xffff; } break; + STBI__CASE(4,1) { dest[0]=stbi__compute_y_16(src[0],src[1],src[2]); } break; + STBI__CASE(4,2) { dest[0]=stbi__compute_y_16(src[0],src[1],src[2]); dest[1] = src[3]; } break; + STBI__CASE(4,3) { dest[0]=src[0];dest[1]=src[1];dest[2]=src[2]; } break; + default: STBI_ASSERT(0); + } + #undef STBI__CASE + } + + STBI_FREE(data); + return good; +} +#endif + +#ifndef STBI_NO_LINEAR +static float *stbi__ldr_to_hdr(stbi_uc *data, int x, int y, int comp) +{ + int i,k,n; + float *output; + if (!data) return NULL; + output = (float *) stbi__malloc_mad4(x, y, comp, sizeof(float), 0); + if (output == NULL) { STBI_FREE(data); return stbi__errpf("outofmem", "Out of memory"); } + // compute number of non-alpha components + if (comp & 1) n = comp; else n = comp-1; + for (i=0; i < x*y; ++i) { + for (k=0; k < n; ++k) { + output[i*comp + k] = (float) (pow(data[i*comp+k]/255.0f, stbi__l2h_gamma) * stbi__l2h_scale); + } + } + if (n < comp) { + for (i=0; i < x*y; ++i) { + output[i*comp + n] = data[i*comp + n]/255.0f; + } + } + STBI_FREE(data); + return output; +} +#endif + +#ifndef STBI_NO_HDR +#define stbi__float2int(x) ((int) (x)) +static stbi_uc *stbi__hdr_to_ldr(float *data, int x, int y, int comp) +{ + int i,k,n; + stbi_uc *output; + if (!data) return NULL; + output = (stbi_uc *) stbi__malloc_mad3(x, y, comp, 0); + if (output == NULL) { STBI_FREE(data); return stbi__errpuc("outofmem", "Out of memory"); } + // compute number of non-alpha components + if (comp & 1) n = comp; else n = comp-1; + for (i=0; i < x*y; ++i) { + for (k=0; k < n; ++k) { + float z = (float) pow(data[i*comp+k]*stbi__h2l_scale_i, stbi__h2l_gamma_i) * 255 + 0.5f; + if (z < 0) z = 0; + if (z > 255) z = 255; + output[i*comp + k] = (stbi_uc) stbi__float2int(z); + } + if (k < comp) { + float z = data[i*comp+k] * 255 + 0.5f; + if (z < 0) z = 0; + if (z > 255) z = 255; + output[i*comp + k] = (stbi_uc) stbi__float2int(z); + } + } + STBI_FREE(data); + return output; +} +#endif + +////////////////////////////////////////////////////////////////////////////// +// +// "baseline" JPEG/JFIF decoder +// +// simple implementation +// - doesn't support delayed output of y-dimension +// - simple interface (only one output format: 8-bit interleaved RGB) +// - doesn't try to recover corrupt jpegs +// - doesn't allow partial loading, loading multiple at once +// - still fast on x86 (copying globals into locals doesn't help x86) +// - allocates lots of intermediate memory (full size of all components) +// - non-interleaved case requires this anyway +// - allows good upsampling (see next) +// high-quality +// - upsampled channels are bilinearly interpolated, even across blocks +// - quality integer IDCT derived from IJG's 'slow' +// performance +// - fast huffman; reasonable integer IDCT +// - some SIMD kernels for common paths on targets with SSE2/NEON +// - uses a lot of intermediate memory, could cache poorly + +#ifndef STBI_NO_JPEG + +// huffman decoding acceleration +#define FAST_BITS 9 // larger handles more cases; smaller stomps less cache + +typedef struct +{ + stbi_uc fast[1 << FAST_BITS]; + // weirdly, repacking this into AoS is a 10% speed loss, instead of a win + stbi__uint16 code[256]; + stbi_uc values[256]; + stbi_uc size[257]; + unsigned int maxcode[18]; + int delta[17]; // old 'firstsymbol' - old 'firstcode' +} stbi__huffman; + +typedef struct +{ + stbi__context *s; + stbi__huffman huff_dc[4]; + stbi__huffman huff_ac[4]; + stbi__uint16 dequant[4][64]; + stbi__int16 fast_ac[4][1 << FAST_BITS]; + +// sizes for components, interleaved MCUs + int img_h_max, img_v_max; + int img_mcu_x, img_mcu_y; + int img_mcu_w, img_mcu_h; + +// definition of jpeg image component + struct + { + int id; + int h,v; + int tq; + int hd,ha; + int dc_pred; + + int x,y,w2,h2; + stbi_uc *data; + void *raw_data, *raw_coeff; + stbi_uc *linebuf; + short *coeff; // progressive only + int coeff_w, coeff_h; // number of 8x8 coefficient blocks + } img_comp[4]; + + stbi__uint32 code_buffer; // jpeg entropy-coded buffer + int code_bits; // number of valid bits + unsigned char marker; // marker seen while filling entropy buffer + int nomore; // flag if we saw a marker so must stop + + int progressive; + int spec_start; + int spec_end; + int succ_high; + int succ_low; + int eob_run; + int jfif; + int app14_color_transform; // Adobe APP14 tag + int rgb; + + int scan_n, order[4]; + int restart_interval, todo; + +// kernels + void (*idct_block_kernel)(stbi_uc *out, int out_stride, short data[64]); + void (*YCbCr_to_RGB_kernel)(stbi_uc *out, const stbi_uc *y, const stbi_uc *pcb, const stbi_uc *pcr, int count, int step); + stbi_uc *(*resample_row_hv_2_kernel)(stbi_uc *out, stbi_uc *in_near, stbi_uc *in_far, int w, int hs); +} stbi__jpeg; + +static int stbi__build_huffman(stbi__huffman *h, int *count) +{ + int i,j,k=0; + unsigned int code; + // build size list for each symbol (from JPEG spec) + for (i=0; i < 16; ++i) + for (j=0; j < count[i]; ++j) + h->size[k++] = (stbi_uc) (i+1); + h->size[k] = 0; + + // compute actual symbols (from jpeg spec) + code = 0; + k = 0; + for(j=1; j <= 16; ++j) { + // compute delta to add to code to compute symbol id + h->delta[j] = k - code; + if (h->size[k] == j) { + while (h->size[k] == j) + h->code[k++] = (stbi__uint16) (code++); + if (code-1 >= (1u << j)) return stbi__err("bad code lengths","Corrupt JPEG"); + } + // compute largest code + 1 for this size, preshifted as needed later + h->maxcode[j] = code << (16-j); + code <<= 1; + } + h->maxcode[j] = 0xffffffff; + + // build non-spec acceleration table; 255 is flag for not-accelerated + memset(h->fast, 255, 1 << FAST_BITS); + for (i=0; i < k; ++i) { + int s = h->size[i]; + if (s <= FAST_BITS) { + int c = h->code[i] << (FAST_BITS-s); + int m = 1 << (FAST_BITS-s); + for (j=0; j < m; ++j) { + h->fast[c+j] = (stbi_uc) i; + } + } + } + return 1; +} + +// build a table that decodes both magnitude and value of small ACs in +// one go. +static void stbi__build_fast_ac(stbi__int16 *fast_ac, stbi__huffman *h) +{ + int i; + for (i=0; i < (1 << FAST_BITS); ++i) { + stbi_uc fast = h->fast[i]; + fast_ac[i] = 0; + if (fast < 255) { + int rs = h->values[fast]; + int run = (rs >> 4) & 15; + int magbits = rs & 15; + int len = h->size[fast]; + + if (magbits && len + magbits <= FAST_BITS) { + // magnitude code followed by receive_extend code + int k = ((i << len) & ((1 << FAST_BITS) - 1)) >> (FAST_BITS - magbits); + int m = 1 << (magbits - 1); + if (k < m) k += (~0U << magbits) + 1; + // if the result is small enough, we can fit it in fast_ac table + if (k >= -128 && k <= 127) + fast_ac[i] = (stbi__int16) ((k * 256) + (run * 16) + (len + magbits)); + } + } + } +} + +static void stbi__grow_buffer_unsafe(stbi__jpeg *j) +{ + do { + unsigned int b = j->nomore ? 0 : stbi__get8(j->s); + if (b == 0xff) { + int c = stbi__get8(j->s); + while (c == 0xff) c = stbi__get8(j->s); // consume fill bytes + if (c != 0) { + j->marker = (unsigned char) c; + j->nomore = 1; + return; + } + } + j->code_buffer |= b << (24 - j->code_bits); + j->code_bits += 8; + } while (j->code_bits <= 24); +} + +// (1 << n) - 1 +static const stbi__uint32 stbi__bmask[17]={0,1,3,7,15,31,63,127,255,511,1023,2047,4095,8191,16383,32767,65535}; + +// decode a jpeg huffman value from the bitstream +stbi_inline static int stbi__jpeg_huff_decode(stbi__jpeg *j, stbi__huffman *h) +{ + unsigned int temp; + int c,k; + + if (j->code_bits < 16) stbi__grow_buffer_unsafe(j); + + // look at the top FAST_BITS and determine what symbol ID it is, + // if the code is <= FAST_BITS + c = (j->code_buffer >> (32 - FAST_BITS)) & ((1 << FAST_BITS)-1); + k = h->fast[c]; + if (k < 255) { + int s = h->size[k]; + if (s > j->code_bits) + return -1; + j->code_buffer <<= s; + j->code_bits -= s; + return h->values[k]; + } + + // naive test is to shift the code_buffer down so k bits are + // valid, then test against maxcode. To speed this up, we've + // preshifted maxcode left so that it has (16-k) 0s at the + // end; in other words, regardless of the number of bits, it + // wants to be compared against something shifted to have 16; + // that way we don't need to shift inside the loop. + temp = j->code_buffer >> 16; + for (k=FAST_BITS+1 ; ; ++k) + if (temp < h->maxcode[k]) + break; + if (k == 17) { + // error! code not found + j->code_bits -= 16; + return -1; + } + + if (k > j->code_bits) + return -1; + + // convert the huffman code to the symbol id + c = ((j->code_buffer >> (32 - k)) & stbi__bmask[k]) + h->delta[k]; + STBI_ASSERT((((j->code_buffer) >> (32 - h->size[c])) & stbi__bmask[h->size[c]]) == h->code[c]); + + // convert the id to a symbol + j->code_bits -= k; + j->code_buffer <<= k; + return h->values[c]; +} + +// bias[n] = (-1<code_bits < n) stbi__grow_buffer_unsafe(j); + + sgn = (stbi__int32)j->code_buffer >> 31; // sign bit is always in MSB + k = stbi_lrot(j->code_buffer, n); + STBI_ASSERT(n >= 0 && n < (int) (sizeof(stbi__bmask)/sizeof(*stbi__bmask))); + j->code_buffer = k & ~stbi__bmask[n]; + k &= stbi__bmask[n]; + j->code_bits -= n; + return k + (stbi__jbias[n] & ~sgn); +} + +// get some unsigned bits +stbi_inline static int stbi__jpeg_get_bits(stbi__jpeg *j, int n) +{ + unsigned int k; + if (j->code_bits < n) stbi__grow_buffer_unsafe(j); + k = stbi_lrot(j->code_buffer, n); + j->code_buffer = k & ~stbi__bmask[n]; + k &= stbi__bmask[n]; + j->code_bits -= n; + return k; +} + +stbi_inline static int stbi__jpeg_get_bit(stbi__jpeg *j) +{ + unsigned int k; + if (j->code_bits < 1) stbi__grow_buffer_unsafe(j); + k = j->code_buffer; + j->code_buffer <<= 1; + --j->code_bits; + return k & 0x80000000; +} + +// given a value that's at position X in the zigzag stream, +// where does it appear in the 8x8 matrix coded as row-major? +static const stbi_uc stbi__jpeg_dezigzag[64+15] = +{ + 0, 1, 8, 16, 9, 2, 3, 10, + 17, 24, 32, 25, 18, 11, 4, 5, + 12, 19, 26, 33, 40, 48, 41, 34, + 27, 20, 13, 6, 7, 14, 21, 28, + 35, 42, 49, 56, 57, 50, 43, 36, + 29, 22, 15, 23, 30, 37, 44, 51, + 58, 59, 52, 45, 38, 31, 39, 46, + 53, 60, 61, 54, 47, 55, 62, 63, + // let corrupt input sample past end + 63, 63, 63, 63, 63, 63, 63, 63, + 63, 63, 63, 63, 63, 63, 63 +}; + +// decode one 64-entry block-- +static int stbi__jpeg_decode_block(stbi__jpeg *j, short data[64], stbi__huffman *hdc, stbi__huffman *hac, stbi__int16 *fac, int b, stbi__uint16 *dequant) +{ + int diff,dc,k; + int t; + + if (j->code_bits < 16) stbi__grow_buffer_unsafe(j); + t = stbi__jpeg_huff_decode(j, hdc); + if (t < 0) return stbi__err("bad huffman code","Corrupt JPEG"); + + // 0 all the ac values now so we can do it 32-bits at a time + memset(data,0,64*sizeof(data[0])); + + diff = t ? stbi__extend_receive(j, t) : 0; + dc = j->img_comp[b].dc_pred + diff; + j->img_comp[b].dc_pred = dc; + data[0] = (short) (dc * dequant[0]); + + // decode AC components, see JPEG spec + k = 1; + do { + unsigned int zig; + int c,r,s; + if (j->code_bits < 16) stbi__grow_buffer_unsafe(j); + c = (j->code_buffer >> (32 - FAST_BITS)) & ((1 << FAST_BITS)-1); + r = fac[c]; + if (r) { // fast-AC path + k += (r >> 4) & 15; // run + s = r & 15; // combined length + j->code_buffer <<= s; + j->code_bits -= s; + // decode into unzigzag'd location + zig = stbi__jpeg_dezigzag[k++]; + data[zig] = (short) ((r >> 8) * dequant[zig]); + } else { + int rs = stbi__jpeg_huff_decode(j, hac); + if (rs < 0) return stbi__err("bad huffman code","Corrupt JPEG"); + s = rs & 15; + r = rs >> 4; + if (s == 0) { + if (rs != 0xf0) break; // end block + k += 16; + } else { + k += r; + // decode into unzigzag'd location + zig = stbi__jpeg_dezigzag[k++]; + data[zig] = (short) (stbi__extend_receive(j,s) * dequant[zig]); + } + } + } while (k < 64); + return 1; +} + +static int stbi__jpeg_decode_block_prog_dc(stbi__jpeg *j, short data[64], stbi__huffman *hdc, int b) +{ + int diff,dc; + int t; + if (j->spec_end != 0) return stbi__err("can't merge dc and ac", "Corrupt JPEG"); + + if (j->code_bits < 16) stbi__grow_buffer_unsafe(j); + + if (j->succ_high == 0) { + // first scan for DC coefficient, must be first + memset(data,0,64*sizeof(data[0])); // 0 all the ac values now + t = stbi__jpeg_huff_decode(j, hdc); + diff = t ? stbi__extend_receive(j, t) : 0; + + dc = j->img_comp[b].dc_pred + diff; + j->img_comp[b].dc_pred = dc; + data[0] = (short) (dc << j->succ_low); + } else { + // refinement scan for DC coefficient + if (stbi__jpeg_get_bit(j)) + data[0] += (short) (1 << j->succ_low); + } + return 1; +} + +// @OPTIMIZE: store non-zigzagged during the decode passes, +// and only de-zigzag when dequantizing +static int stbi__jpeg_decode_block_prog_ac(stbi__jpeg *j, short data[64], stbi__huffman *hac, stbi__int16 *fac) +{ + int k; + if (j->spec_start == 0) return stbi__err("can't merge dc and ac", "Corrupt JPEG"); + + if (j->succ_high == 0) { + int shift = j->succ_low; + + if (j->eob_run) { + --j->eob_run; + return 1; + } + + k = j->spec_start; + do { + unsigned int zig; + int c,r,s; + if (j->code_bits < 16) stbi__grow_buffer_unsafe(j); + c = (j->code_buffer >> (32 - FAST_BITS)) & ((1 << FAST_BITS)-1); + r = fac[c]; + if (r) { // fast-AC path + k += (r >> 4) & 15; // run + s = r & 15; // combined length + j->code_buffer <<= s; + j->code_bits -= s; + zig = stbi__jpeg_dezigzag[k++]; + data[zig] = (short) ((r >> 8) << shift); + } else { + int rs = stbi__jpeg_huff_decode(j, hac); + if (rs < 0) return stbi__err("bad huffman code","Corrupt JPEG"); + s = rs & 15; + r = rs >> 4; + if (s == 0) { + if (r < 15) { + j->eob_run = (1 << r); + if (r) + j->eob_run += stbi__jpeg_get_bits(j, r); + --j->eob_run; + break; + } + k += 16; + } else { + k += r; + zig = stbi__jpeg_dezigzag[k++]; + data[zig] = (short) (stbi__extend_receive(j,s) << shift); + } + } + } while (k <= j->spec_end); + } else { + // refinement scan for these AC coefficients + + short bit = (short) (1 << j->succ_low); + + if (j->eob_run) { + --j->eob_run; + for (k = j->spec_start; k <= j->spec_end; ++k) { + short *p = &data[stbi__jpeg_dezigzag[k]]; + if (*p != 0) + if (stbi__jpeg_get_bit(j)) + if ((*p & bit)==0) { + if (*p > 0) + *p += bit; + else + *p -= bit; + } + } + } else { + k = j->spec_start; + do { + int r,s; + int rs = stbi__jpeg_huff_decode(j, hac); // @OPTIMIZE see if we can use the fast path here, advance-by-r is so slow, eh + if (rs < 0) return stbi__err("bad huffman code","Corrupt JPEG"); + s = rs & 15; + r = rs >> 4; + if (s == 0) { + if (r < 15) { + j->eob_run = (1 << r) - 1; + if (r) + j->eob_run += stbi__jpeg_get_bits(j, r); + r = 64; // force end of block + } else { + // r=15 s=0 should write 16 0s, so we just do + // a run of 15 0s and then write s (which is 0), + // so we don't have to do anything special here + } + } else { + if (s != 1) return stbi__err("bad huffman code", "Corrupt JPEG"); + // sign bit + if (stbi__jpeg_get_bit(j)) + s = bit; + else + s = -bit; + } + + // advance by r + while (k <= j->spec_end) { + short *p = &data[stbi__jpeg_dezigzag[k++]]; + if (*p != 0) { + if (stbi__jpeg_get_bit(j)) + if ((*p & bit)==0) { + if (*p > 0) + *p += bit; + else + *p -= bit; + } + } else { + if (r == 0) { + *p = (short) s; + break; + } + --r; + } + } + } while (k <= j->spec_end); + } + } + return 1; +} + +// take a -128..127 value and stbi__clamp it and convert to 0..255 +stbi_inline static stbi_uc stbi__clamp(int x) +{ + // trick to use a single test to catch both cases + if ((unsigned int) x > 255) { + if (x < 0) return 0; + if (x > 255) return 255; + } + return (stbi_uc) x; +} + +#define stbi__f2f(x) ((int) (((x) * 4096 + 0.5))) +#define stbi__fsh(x) ((x) * 4096) + +// derived from jidctint -- DCT_ISLOW +#define STBI__IDCT_1D(s0,s1,s2,s3,s4,s5,s6,s7) \ + int t0,t1,t2,t3,p1,p2,p3,p4,p5,x0,x1,x2,x3; \ + p2 = s2; \ + p3 = s6; \ + p1 = (p2+p3) * stbi__f2f(0.5411961f); \ + t2 = p1 + p3*stbi__f2f(-1.847759065f); \ + t3 = p1 + p2*stbi__f2f( 0.765366865f); \ + p2 = s0; \ + p3 = s4; \ + t0 = stbi__fsh(p2+p3); \ + t1 = stbi__fsh(p2-p3); \ + x0 = t0+t3; \ + x3 = t0-t3; \ + x1 = t1+t2; \ + x2 = t1-t2; \ + t0 = s7; \ + t1 = s5; \ + t2 = s3; \ + t3 = s1; \ + p3 = t0+t2; \ + p4 = t1+t3; \ + p1 = t0+t3; \ + p2 = t1+t2; \ + p5 = (p3+p4)*stbi__f2f( 1.175875602f); \ + t0 = t0*stbi__f2f( 0.298631336f); \ + t1 = t1*stbi__f2f( 2.053119869f); \ + t2 = t2*stbi__f2f( 3.072711026f); \ + t3 = t3*stbi__f2f( 1.501321110f); \ + p1 = p5 + p1*stbi__f2f(-0.899976223f); \ + p2 = p5 + p2*stbi__f2f(-2.562915447f); \ + p3 = p3*stbi__f2f(-1.961570560f); \ + p4 = p4*stbi__f2f(-0.390180644f); \ + t3 += p1+p4; \ + t2 += p2+p3; \ + t1 += p2+p4; \ + t0 += p1+p3; + +static void stbi__idct_block(stbi_uc *out, int out_stride, short data[64]) +{ + int i,val[64],*v=val; + stbi_uc *o; + short *d = data; + + // columns + for (i=0; i < 8; ++i,++d, ++v) { + // if all zeroes, shortcut -- this avoids dequantizing 0s and IDCTing + if (d[ 8]==0 && d[16]==0 && d[24]==0 && d[32]==0 + && d[40]==0 && d[48]==0 && d[56]==0) { + // no shortcut 0 seconds + // (1|2|3|4|5|6|7)==0 0 seconds + // all separate -0.047 seconds + // 1 && 2|3 && 4|5 && 6|7: -0.047 seconds + int dcterm = d[0]*4; + v[0] = v[8] = v[16] = v[24] = v[32] = v[40] = v[48] = v[56] = dcterm; + } else { + STBI__IDCT_1D(d[ 0],d[ 8],d[16],d[24],d[32],d[40],d[48],d[56]) + // constants scaled things up by 1<<12; let's bring them back + // down, but keep 2 extra bits of precision + x0 += 512; x1 += 512; x2 += 512; x3 += 512; + v[ 0] = (x0+t3) >> 10; + v[56] = (x0-t3) >> 10; + v[ 8] = (x1+t2) >> 10; + v[48] = (x1-t2) >> 10; + v[16] = (x2+t1) >> 10; + v[40] = (x2-t1) >> 10; + v[24] = (x3+t0) >> 10; + v[32] = (x3-t0) >> 10; + } + } + + for (i=0, v=val, o=out; i < 8; ++i,v+=8,o+=out_stride) { + // no fast case since the first 1D IDCT spread components out + STBI__IDCT_1D(v[0],v[1],v[2],v[3],v[4],v[5],v[6],v[7]) + // constants scaled things up by 1<<12, plus we had 1<<2 from first + // loop, plus horizontal and vertical each scale by sqrt(8) so together + // we've got an extra 1<<3, so 1<<17 total we need to remove. + // so we want to round that, which means adding 0.5 * 1<<17, + // aka 65536. Also, we'll end up with -128 to 127 that we want + // to encode as 0..255 by adding 128, so we'll add that before the shift + x0 += 65536 + (128<<17); + x1 += 65536 + (128<<17); + x2 += 65536 + (128<<17); + x3 += 65536 + (128<<17); + // tried computing the shifts into temps, or'ing the temps to see + // if any were out of range, but that was slower + o[0] = stbi__clamp((x0+t3) >> 17); + o[7] = stbi__clamp((x0-t3) >> 17); + o[1] = stbi__clamp((x1+t2) >> 17); + o[6] = stbi__clamp((x1-t2) >> 17); + o[2] = stbi__clamp((x2+t1) >> 17); + o[5] = stbi__clamp((x2-t1) >> 17); + o[3] = stbi__clamp((x3+t0) >> 17); + o[4] = stbi__clamp((x3-t0) >> 17); + } +} + +#ifdef STBI_SSE2 +// sse2 integer IDCT. not the fastest possible implementation but it +// produces bit-identical results to the generic C version so it's +// fully "transparent". +static void stbi__idct_simd(stbi_uc *out, int out_stride, short data[64]) +{ + // This is constructed to match our regular (generic) integer IDCT exactly. + __m128i row0, row1, row2, row3, row4, row5, row6, row7; + __m128i tmp; + + // dot product constant: even elems=x, odd elems=y + #define dct_const(x,y) _mm_setr_epi16((x),(y),(x),(y),(x),(y),(x),(y)) + + // out(0) = c0[even]*x + c0[odd]*y (c0, x, y 16-bit, out 32-bit) + // out(1) = c1[even]*x + c1[odd]*y + #define dct_rot(out0,out1, x,y,c0,c1) \ + __m128i c0##lo = _mm_unpacklo_epi16((x),(y)); \ + __m128i c0##hi = _mm_unpackhi_epi16((x),(y)); \ + __m128i out0##_l = _mm_madd_epi16(c0##lo, c0); \ + __m128i out0##_h = _mm_madd_epi16(c0##hi, c0); \ + __m128i out1##_l = _mm_madd_epi16(c0##lo, c1); \ + __m128i out1##_h = _mm_madd_epi16(c0##hi, c1) + + // out = in << 12 (in 16-bit, out 32-bit) + #define dct_widen(out, in) \ + __m128i out##_l = _mm_srai_epi32(_mm_unpacklo_epi16(_mm_setzero_si128(), (in)), 4); \ + __m128i out##_h = _mm_srai_epi32(_mm_unpackhi_epi16(_mm_setzero_si128(), (in)), 4) + + // wide add + #define dct_wadd(out, a, b) \ + __m128i out##_l = _mm_add_epi32(a##_l, b##_l); \ + __m128i out##_h = _mm_add_epi32(a##_h, b##_h) + + // wide sub + #define dct_wsub(out, a, b) \ + __m128i out##_l = _mm_sub_epi32(a##_l, b##_l); \ + __m128i out##_h = _mm_sub_epi32(a##_h, b##_h) + + // butterfly a/b, add bias, then shift by "s" and pack + #define dct_bfly32o(out0, out1, a,b,bias,s) \ + { \ + __m128i abiased_l = _mm_add_epi32(a##_l, bias); \ + __m128i abiased_h = _mm_add_epi32(a##_h, bias); \ + dct_wadd(sum, abiased, b); \ + dct_wsub(dif, abiased, b); \ + out0 = _mm_packs_epi32(_mm_srai_epi32(sum_l, s), _mm_srai_epi32(sum_h, s)); \ + out1 = _mm_packs_epi32(_mm_srai_epi32(dif_l, s), _mm_srai_epi32(dif_h, s)); \ + } + + // 8-bit interleave step (for transposes) + #define dct_interleave8(a, b) \ + tmp = a; \ + a = _mm_unpacklo_epi8(a, b); \ + b = _mm_unpackhi_epi8(tmp, b) + + // 16-bit interleave step (for transposes) + #define dct_interleave16(a, b) \ + tmp = a; \ + a = _mm_unpacklo_epi16(a, b); \ + b = _mm_unpackhi_epi16(tmp, b) + + #define dct_pass(bias,shift) \ + { \ + /* even part */ \ + dct_rot(t2e,t3e, row2,row6, rot0_0,rot0_1); \ + __m128i sum04 = _mm_add_epi16(row0, row4); \ + __m128i dif04 = _mm_sub_epi16(row0, row4); \ + dct_widen(t0e, sum04); \ + dct_widen(t1e, dif04); \ + dct_wadd(x0, t0e, t3e); \ + dct_wsub(x3, t0e, t3e); \ + dct_wadd(x1, t1e, t2e); \ + dct_wsub(x2, t1e, t2e); \ + /* odd part */ \ + dct_rot(y0o,y2o, row7,row3, rot2_0,rot2_1); \ + dct_rot(y1o,y3o, row5,row1, rot3_0,rot3_1); \ + __m128i sum17 = _mm_add_epi16(row1, row7); \ + __m128i sum35 = _mm_add_epi16(row3, row5); \ + dct_rot(y4o,y5o, sum17,sum35, rot1_0,rot1_1); \ + dct_wadd(x4, y0o, y4o); \ + dct_wadd(x5, y1o, y5o); \ + dct_wadd(x6, y2o, y5o); \ + dct_wadd(x7, y3o, y4o); \ + dct_bfly32o(row0,row7, x0,x7,bias,shift); \ + dct_bfly32o(row1,row6, x1,x6,bias,shift); \ + dct_bfly32o(row2,row5, x2,x5,bias,shift); \ + dct_bfly32o(row3,row4, x3,x4,bias,shift); \ + } + + __m128i rot0_0 = dct_const(stbi__f2f(0.5411961f), stbi__f2f(0.5411961f) + stbi__f2f(-1.847759065f)); + __m128i rot0_1 = dct_const(stbi__f2f(0.5411961f) + stbi__f2f( 0.765366865f), stbi__f2f(0.5411961f)); + __m128i rot1_0 = dct_const(stbi__f2f(1.175875602f) + stbi__f2f(-0.899976223f), stbi__f2f(1.175875602f)); + __m128i rot1_1 = dct_const(stbi__f2f(1.175875602f), stbi__f2f(1.175875602f) + stbi__f2f(-2.562915447f)); + __m128i rot2_0 = dct_const(stbi__f2f(-1.961570560f) + stbi__f2f( 0.298631336f), stbi__f2f(-1.961570560f)); + __m128i rot2_1 = dct_const(stbi__f2f(-1.961570560f), stbi__f2f(-1.961570560f) + stbi__f2f( 3.072711026f)); + __m128i rot3_0 = dct_const(stbi__f2f(-0.390180644f) + stbi__f2f( 2.053119869f), stbi__f2f(-0.390180644f)); + __m128i rot3_1 = dct_const(stbi__f2f(-0.390180644f), stbi__f2f(-0.390180644f) + stbi__f2f( 1.501321110f)); + + // rounding biases in column/row passes, see stbi__idct_block for explanation. + __m128i bias_0 = _mm_set1_epi32(512); + __m128i bias_1 = _mm_set1_epi32(65536 + (128<<17)); + + // load + row0 = _mm_load_si128((const __m128i *) (data + 0*8)); + row1 = _mm_load_si128((const __m128i *) (data + 1*8)); + row2 = _mm_load_si128((const __m128i *) (data + 2*8)); + row3 = _mm_load_si128((const __m128i *) (data + 3*8)); + row4 = _mm_load_si128((const __m128i *) (data + 4*8)); + row5 = _mm_load_si128((const __m128i *) (data + 5*8)); + row6 = _mm_load_si128((const __m128i *) (data + 6*8)); + row7 = _mm_load_si128((const __m128i *) (data + 7*8)); + + // column pass + dct_pass(bias_0, 10); + + { + // 16bit 8x8 transpose pass 1 + dct_interleave16(row0, row4); + dct_interleave16(row1, row5); + dct_interleave16(row2, row6); + dct_interleave16(row3, row7); + + // transpose pass 2 + dct_interleave16(row0, row2); + dct_interleave16(row1, row3); + dct_interleave16(row4, row6); + dct_interleave16(row5, row7); + + // transpose pass 3 + dct_interleave16(row0, row1); + dct_interleave16(row2, row3); + dct_interleave16(row4, row5); + dct_interleave16(row6, row7); + } + + // row pass + dct_pass(bias_1, 17); + + { + // pack + __m128i p0 = _mm_packus_epi16(row0, row1); // a0a1a2a3...a7b0b1b2b3...b7 + __m128i p1 = _mm_packus_epi16(row2, row3); + __m128i p2 = _mm_packus_epi16(row4, row5); + __m128i p3 = _mm_packus_epi16(row6, row7); + + // 8bit 8x8 transpose pass 1 + dct_interleave8(p0, p2); // a0e0a1e1... + dct_interleave8(p1, p3); // c0g0c1g1... + + // transpose pass 2 + dct_interleave8(p0, p1); // a0c0e0g0... + dct_interleave8(p2, p3); // b0d0f0h0... + + // transpose pass 3 + dct_interleave8(p0, p2); // a0b0c0d0... + dct_interleave8(p1, p3); // a4b4c4d4... + + // store + _mm_storel_epi64((__m128i *) out, p0); out += out_stride; + _mm_storel_epi64((__m128i *) out, _mm_shuffle_epi32(p0, 0x4e)); out += out_stride; + _mm_storel_epi64((__m128i *) out, p2); out += out_stride; + _mm_storel_epi64((__m128i *) out, _mm_shuffle_epi32(p2, 0x4e)); out += out_stride; + _mm_storel_epi64((__m128i *) out, p1); out += out_stride; + _mm_storel_epi64((__m128i *) out, _mm_shuffle_epi32(p1, 0x4e)); out += out_stride; + _mm_storel_epi64((__m128i *) out, p3); out += out_stride; + _mm_storel_epi64((__m128i *) out, _mm_shuffle_epi32(p3, 0x4e)); + } + +#undef dct_const +#undef dct_rot +#undef dct_widen +#undef dct_wadd +#undef dct_wsub +#undef dct_bfly32o +#undef dct_interleave8 +#undef dct_interleave16 +#undef dct_pass +} + +#endif // STBI_SSE2 + +#ifdef STBI_NEON + +// NEON integer IDCT. should produce bit-identical +// results to the generic C version. +static void stbi__idct_simd(stbi_uc *out, int out_stride, short data[64]) +{ + int16x8_t row0, row1, row2, row3, row4, row5, row6, row7; + + int16x4_t rot0_0 = vdup_n_s16(stbi__f2f(0.5411961f)); + int16x4_t rot0_1 = vdup_n_s16(stbi__f2f(-1.847759065f)); + int16x4_t rot0_2 = vdup_n_s16(stbi__f2f( 0.765366865f)); + int16x4_t rot1_0 = vdup_n_s16(stbi__f2f( 1.175875602f)); + int16x4_t rot1_1 = vdup_n_s16(stbi__f2f(-0.899976223f)); + int16x4_t rot1_2 = vdup_n_s16(stbi__f2f(-2.562915447f)); + int16x4_t rot2_0 = vdup_n_s16(stbi__f2f(-1.961570560f)); + int16x4_t rot2_1 = vdup_n_s16(stbi__f2f(-0.390180644f)); + int16x4_t rot3_0 = vdup_n_s16(stbi__f2f( 0.298631336f)); + int16x4_t rot3_1 = vdup_n_s16(stbi__f2f( 2.053119869f)); + int16x4_t rot3_2 = vdup_n_s16(stbi__f2f( 3.072711026f)); + int16x4_t rot3_3 = vdup_n_s16(stbi__f2f( 1.501321110f)); + +#define dct_long_mul(out, inq, coeff) \ + int32x4_t out##_l = vmull_s16(vget_low_s16(inq), coeff); \ + int32x4_t out##_h = vmull_s16(vget_high_s16(inq), coeff) + +#define dct_long_mac(out, acc, inq, coeff) \ + int32x4_t out##_l = vmlal_s16(acc##_l, vget_low_s16(inq), coeff); \ + int32x4_t out##_h = vmlal_s16(acc##_h, vget_high_s16(inq), coeff) + +#define dct_widen(out, inq) \ + int32x4_t out##_l = vshll_n_s16(vget_low_s16(inq), 12); \ + int32x4_t out##_h = vshll_n_s16(vget_high_s16(inq), 12) + +// wide add +#define dct_wadd(out, a, b) \ + int32x4_t out##_l = vaddq_s32(a##_l, b##_l); \ + int32x4_t out##_h = vaddq_s32(a##_h, b##_h) + +// wide sub +#define dct_wsub(out, a, b) \ + int32x4_t out##_l = vsubq_s32(a##_l, b##_l); \ + int32x4_t out##_h = vsubq_s32(a##_h, b##_h) + +// butterfly a/b, then shift using "shiftop" by "s" and pack +#define dct_bfly32o(out0,out1, a,b,shiftop,s) \ + { \ + dct_wadd(sum, a, b); \ + dct_wsub(dif, a, b); \ + out0 = vcombine_s16(shiftop(sum_l, s), shiftop(sum_h, s)); \ + out1 = vcombine_s16(shiftop(dif_l, s), shiftop(dif_h, s)); \ + } + +#define dct_pass(shiftop, shift) \ + { \ + /* even part */ \ + int16x8_t sum26 = vaddq_s16(row2, row6); \ + dct_long_mul(p1e, sum26, rot0_0); \ + dct_long_mac(t2e, p1e, row6, rot0_1); \ + dct_long_mac(t3e, p1e, row2, rot0_2); \ + int16x8_t sum04 = vaddq_s16(row0, row4); \ + int16x8_t dif04 = vsubq_s16(row0, row4); \ + dct_widen(t0e, sum04); \ + dct_widen(t1e, dif04); \ + dct_wadd(x0, t0e, t3e); \ + dct_wsub(x3, t0e, t3e); \ + dct_wadd(x1, t1e, t2e); \ + dct_wsub(x2, t1e, t2e); \ + /* odd part */ \ + int16x8_t sum15 = vaddq_s16(row1, row5); \ + int16x8_t sum17 = vaddq_s16(row1, row7); \ + int16x8_t sum35 = vaddq_s16(row3, row5); \ + int16x8_t sum37 = vaddq_s16(row3, row7); \ + int16x8_t sumodd = vaddq_s16(sum17, sum35); \ + dct_long_mul(p5o, sumodd, rot1_0); \ + dct_long_mac(p1o, p5o, sum17, rot1_1); \ + dct_long_mac(p2o, p5o, sum35, rot1_2); \ + dct_long_mul(p3o, sum37, rot2_0); \ + dct_long_mul(p4o, sum15, rot2_1); \ + dct_wadd(sump13o, p1o, p3o); \ + dct_wadd(sump24o, p2o, p4o); \ + dct_wadd(sump23o, p2o, p3o); \ + dct_wadd(sump14o, p1o, p4o); \ + dct_long_mac(x4, sump13o, row7, rot3_0); \ + dct_long_mac(x5, sump24o, row5, rot3_1); \ + dct_long_mac(x6, sump23o, row3, rot3_2); \ + dct_long_mac(x7, sump14o, row1, rot3_3); \ + dct_bfly32o(row0,row7, x0,x7,shiftop,shift); \ + dct_bfly32o(row1,row6, x1,x6,shiftop,shift); \ + dct_bfly32o(row2,row5, x2,x5,shiftop,shift); \ + dct_bfly32o(row3,row4, x3,x4,shiftop,shift); \ + } + + // load + row0 = vld1q_s16(data + 0*8); + row1 = vld1q_s16(data + 1*8); + row2 = vld1q_s16(data + 2*8); + row3 = vld1q_s16(data + 3*8); + row4 = vld1q_s16(data + 4*8); + row5 = vld1q_s16(data + 5*8); + row6 = vld1q_s16(data + 6*8); + row7 = vld1q_s16(data + 7*8); + + // add DC bias + row0 = vaddq_s16(row0, vsetq_lane_s16(1024, vdupq_n_s16(0), 0)); + + // column pass + dct_pass(vrshrn_n_s32, 10); + + // 16bit 8x8 transpose + { +// these three map to a single VTRN.16, VTRN.32, and VSWP, respectively. +// whether compilers actually get this is another story, sadly. +#define dct_trn16(x, y) { int16x8x2_t t = vtrnq_s16(x, y); x = t.val[0]; y = t.val[1]; } +#define dct_trn32(x, y) { int32x4x2_t t = vtrnq_s32(vreinterpretq_s32_s16(x), vreinterpretq_s32_s16(y)); x = vreinterpretq_s16_s32(t.val[0]); y = vreinterpretq_s16_s32(t.val[1]); } +#define dct_trn64(x, y) { int16x8_t x0 = x; int16x8_t y0 = y; x = vcombine_s16(vget_low_s16(x0), vget_low_s16(y0)); y = vcombine_s16(vget_high_s16(x0), vget_high_s16(y0)); } + + // pass 1 + dct_trn16(row0, row1); // a0b0a2b2a4b4a6b6 + dct_trn16(row2, row3); + dct_trn16(row4, row5); + dct_trn16(row6, row7); + + // pass 2 + dct_trn32(row0, row2); // a0b0c0d0a4b4c4d4 + dct_trn32(row1, row3); + dct_trn32(row4, row6); + dct_trn32(row5, row7); + + // pass 3 + dct_trn64(row0, row4); // a0b0c0d0e0f0g0h0 + dct_trn64(row1, row5); + dct_trn64(row2, row6); + dct_trn64(row3, row7); + +#undef dct_trn16 +#undef dct_trn32 +#undef dct_trn64 + } + + // row pass + // vrshrn_n_s32 only supports shifts up to 16, we need + // 17. so do a non-rounding shift of 16 first then follow + // up with a rounding shift by 1. + dct_pass(vshrn_n_s32, 16); + + { + // pack and round + uint8x8_t p0 = vqrshrun_n_s16(row0, 1); + uint8x8_t p1 = vqrshrun_n_s16(row1, 1); + uint8x8_t p2 = vqrshrun_n_s16(row2, 1); + uint8x8_t p3 = vqrshrun_n_s16(row3, 1); + uint8x8_t p4 = vqrshrun_n_s16(row4, 1); + uint8x8_t p5 = vqrshrun_n_s16(row5, 1); + uint8x8_t p6 = vqrshrun_n_s16(row6, 1); + uint8x8_t p7 = vqrshrun_n_s16(row7, 1); + + // again, these can translate into one instruction, but often don't. +#define dct_trn8_8(x, y) { uint8x8x2_t t = vtrn_u8(x, y); x = t.val[0]; y = t.val[1]; } +#define dct_trn8_16(x, y) { uint16x4x2_t t = vtrn_u16(vreinterpret_u16_u8(x), vreinterpret_u16_u8(y)); x = vreinterpret_u8_u16(t.val[0]); y = vreinterpret_u8_u16(t.val[1]); } +#define dct_trn8_32(x, y) { uint32x2x2_t t = vtrn_u32(vreinterpret_u32_u8(x), vreinterpret_u32_u8(y)); x = vreinterpret_u8_u32(t.val[0]); y = vreinterpret_u8_u32(t.val[1]); } + + // sadly can't use interleaved stores here since we only write + // 8 bytes to each scan line! + + // 8x8 8-bit transpose pass 1 + dct_trn8_8(p0, p1); + dct_trn8_8(p2, p3); + dct_trn8_8(p4, p5); + dct_trn8_8(p6, p7); + + // pass 2 + dct_trn8_16(p0, p2); + dct_trn8_16(p1, p3); + dct_trn8_16(p4, p6); + dct_trn8_16(p5, p7); + + // pass 3 + dct_trn8_32(p0, p4); + dct_trn8_32(p1, p5); + dct_trn8_32(p2, p6); + dct_trn8_32(p3, p7); + + // store + vst1_u8(out, p0); out += out_stride; + vst1_u8(out, p1); out += out_stride; + vst1_u8(out, p2); out += out_stride; + vst1_u8(out, p3); out += out_stride; + vst1_u8(out, p4); out += out_stride; + vst1_u8(out, p5); out += out_stride; + vst1_u8(out, p6); out += out_stride; + vst1_u8(out, p7); + +#undef dct_trn8_8 +#undef dct_trn8_16 +#undef dct_trn8_32 + } + +#undef dct_long_mul +#undef dct_long_mac +#undef dct_widen +#undef dct_wadd +#undef dct_wsub +#undef dct_bfly32o +#undef dct_pass +} + +#endif // STBI_NEON + +#define STBI__MARKER_none 0xff +// if there's a pending marker from the entropy stream, return that +// otherwise, fetch from the stream and get a marker. if there's no +// marker, return 0xff, which is never a valid marker value +static stbi_uc stbi__get_marker(stbi__jpeg *j) +{ + stbi_uc x; + if (j->marker != STBI__MARKER_none) { x = j->marker; j->marker = STBI__MARKER_none; return x; } + x = stbi__get8(j->s); + if (x != 0xff) return STBI__MARKER_none; + while (x == 0xff) + x = stbi__get8(j->s); // consume repeated 0xff fill bytes + return x; +} + +// in each scan, we'll have scan_n components, and the order +// of the components is specified by order[] +#define STBI__RESTART(x) ((x) >= 0xd0 && (x) <= 0xd7) + +// after a restart interval, stbi__jpeg_reset the entropy decoder and +// the dc prediction +static void stbi__jpeg_reset(stbi__jpeg *j) +{ + j->code_bits = 0; + j->code_buffer = 0; + j->nomore = 0; + j->img_comp[0].dc_pred = j->img_comp[1].dc_pred = j->img_comp[2].dc_pred = j->img_comp[3].dc_pred = 0; + j->marker = STBI__MARKER_none; + j->todo = j->restart_interval ? j->restart_interval : 0x7fffffff; + j->eob_run = 0; + // no more than 1<<31 MCUs if no restart_interal? that's plenty safe, + // since we don't even allow 1<<30 pixels +} + +static int stbi__parse_entropy_coded_data(stbi__jpeg *z) +{ + stbi__jpeg_reset(z); + if (!z->progressive) { + if (z->scan_n == 1) { + int i,j; + STBI_SIMD_ALIGN(short, data[64]); + int n = z->order[0]; + // non-interleaved data, we just need to process one block at a time, + // in trivial scanline order + // number of blocks to do just depends on how many actual "pixels" this + // component has, independent of interleaved MCU blocking and such + int w = (z->img_comp[n].x+7) >> 3; + int h = (z->img_comp[n].y+7) >> 3; + for (j=0; j < h; ++j) { + for (i=0; i < w; ++i) { + int ha = z->img_comp[n].ha; + if (!stbi__jpeg_decode_block(z, data, z->huff_dc+z->img_comp[n].hd, z->huff_ac+ha, z->fast_ac[ha], n, z->dequant[z->img_comp[n].tq])) return 0; + z->idct_block_kernel(z->img_comp[n].data+z->img_comp[n].w2*j*8+i*8, z->img_comp[n].w2, data); + // every data block is an MCU, so countdown the restart interval + if (--z->todo <= 0) { + if (z->code_bits < 24) stbi__grow_buffer_unsafe(z); + // if it's NOT a restart, then just bail, so we get corrupt data + // rather than no data + if (!STBI__RESTART(z->marker)) return 1; + stbi__jpeg_reset(z); + } + } + } + return 1; + } else { // interleaved + int i,j,k,x,y; + STBI_SIMD_ALIGN(short, data[64]); + for (j=0; j < z->img_mcu_y; ++j) { + for (i=0; i < z->img_mcu_x; ++i) { + // scan an interleaved mcu... process scan_n components in order + for (k=0; k < z->scan_n; ++k) { + int n = z->order[k]; + // scan out an mcu's worth of this component; that's just determined + // by the basic H and V specified for the component + for (y=0; y < z->img_comp[n].v; ++y) { + for (x=0; x < z->img_comp[n].h; ++x) { + int x2 = (i*z->img_comp[n].h + x)*8; + int y2 = (j*z->img_comp[n].v + y)*8; + int ha = z->img_comp[n].ha; + if (!stbi__jpeg_decode_block(z, data, z->huff_dc+z->img_comp[n].hd, z->huff_ac+ha, z->fast_ac[ha], n, z->dequant[z->img_comp[n].tq])) return 0; + z->idct_block_kernel(z->img_comp[n].data+z->img_comp[n].w2*y2+x2, z->img_comp[n].w2, data); + } + } + } + // after all interleaved components, that's an interleaved MCU, + // so now count down the restart interval + if (--z->todo <= 0) { + if (z->code_bits < 24) stbi__grow_buffer_unsafe(z); + if (!STBI__RESTART(z->marker)) return 1; + stbi__jpeg_reset(z); + } + } + } + return 1; + } + } else { + if (z->scan_n == 1) { + int i,j; + int n = z->order[0]; + // non-interleaved data, we just need to process one block at a time, + // in trivial scanline order + // number of blocks to do just depends on how many actual "pixels" this + // component has, independent of interleaved MCU blocking and such + int w = (z->img_comp[n].x+7) >> 3; + int h = (z->img_comp[n].y+7) >> 3; + for (j=0; j < h; ++j) { + for (i=0; i < w; ++i) { + short *data = z->img_comp[n].coeff + 64 * (i + j * z->img_comp[n].coeff_w); + if (z->spec_start == 0) { + if (!stbi__jpeg_decode_block_prog_dc(z, data, &z->huff_dc[z->img_comp[n].hd], n)) + return 0; + } else { + int ha = z->img_comp[n].ha; + if (!stbi__jpeg_decode_block_prog_ac(z, data, &z->huff_ac[ha], z->fast_ac[ha])) + return 0; + } + // every data block is an MCU, so countdown the restart interval + if (--z->todo <= 0) { + if (z->code_bits < 24) stbi__grow_buffer_unsafe(z); + if (!STBI__RESTART(z->marker)) return 1; + stbi__jpeg_reset(z); + } + } + } + return 1; + } else { // interleaved + int i,j,k,x,y; + for (j=0; j < z->img_mcu_y; ++j) { + for (i=0; i < z->img_mcu_x; ++i) { + // scan an interleaved mcu... process scan_n components in order + for (k=0; k < z->scan_n; ++k) { + int n = z->order[k]; + // scan out an mcu's worth of this component; that's just determined + // by the basic H and V specified for the component + for (y=0; y < z->img_comp[n].v; ++y) { + for (x=0; x < z->img_comp[n].h; ++x) { + int x2 = (i*z->img_comp[n].h + x); + int y2 = (j*z->img_comp[n].v + y); + short *data = z->img_comp[n].coeff + 64 * (x2 + y2 * z->img_comp[n].coeff_w); + if (!stbi__jpeg_decode_block_prog_dc(z, data, &z->huff_dc[z->img_comp[n].hd], n)) + return 0; + } + } + } + // after all interleaved components, that's an interleaved MCU, + // so now count down the restart interval + if (--z->todo <= 0) { + if (z->code_bits < 24) stbi__grow_buffer_unsafe(z); + if (!STBI__RESTART(z->marker)) return 1; + stbi__jpeg_reset(z); + } + } + } + return 1; + } + } +} + +static void stbi__jpeg_dequantize(short *data, stbi__uint16 *dequant) +{ + int i; + for (i=0; i < 64; ++i) + data[i] *= dequant[i]; +} + +static void stbi__jpeg_finish(stbi__jpeg *z) +{ + if (z->progressive) { + // dequantize and idct the data + int i,j,n; + for (n=0; n < z->s->img_n; ++n) { + int w = (z->img_comp[n].x+7) >> 3; + int h = (z->img_comp[n].y+7) >> 3; + for (j=0; j < h; ++j) { + for (i=0; i < w; ++i) { + short *data = z->img_comp[n].coeff + 64 * (i + j * z->img_comp[n].coeff_w); + stbi__jpeg_dequantize(data, z->dequant[z->img_comp[n].tq]); + z->idct_block_kernel(z->img_comp[n].data+z->img_comp[n].w2*j*8+i*8, z->img_comp[n].w2, data); + } + } + } + } +} + +static int stbi__process_marker(stbi__jpeg *z, int m) +{ + int L; + switch (m) { + case STBI__MARKER_none: // no marker found + return stbi__err("expected marker","Corrupt JPEG"); + + case 0xDD: // DRI - specify restart interval + if (stbi__get16be(z->s) != 4) return stbi__err("bad DRI len","Corrupt JPEG"); + z->restart_interval = stbi__get16be(z->s); + return 1; + + case 0xDB: // DQT - define quantization table + L = stbi__get16be(z->s)-2; + while (L > 0) { + int q = stbi__get8(z->s); + int p = q >> 4, sixteen = (p != 0); + int t = q & 15,i; + if (p != 0 && p != 1) return stbi__err("bad DQT type","Corrupt JPEG"); + if (t > 3) return stbi__err("bad DQT table","Corrupt JPEG"); + + for (i=0; i < 64; ++i) + z->dequant[t][stbi__jpeg_dezigzag[i]] = (stbi__uint16)(sixteen ? stbi__get16be(z->s) : stbi__get8(z->s)); + L -= (sixteen ? 129 : 65); + } + return L==0; + + case 0xC4: // DHT - define huffman table + L = stbi__get16be(z->s)-2; + while (L > 0) { + stbi_uc *v; + int sizes[16],i,n=0; + int q = stbi__get8(z->s); + int tc = q >> 4; + int th = q & 15; + if (tc > 1 || th > 3) return stbi__err("bad DHT header","Corrupt JPEG"); + for (i=0; i < 16; ++i) { + sizes[i] = stbi__get8(z->s); + n += sizes[i]; + } + L -= 17; + if (tc == 0) { + if (!stbi__build_huffman(z->huff_dc+th, sizes)) return 0; + v = z->huff_dc[th].values; + } else { + if (!stbi__build_huffman(z->huff_ac+th, sizes)) return 0; + v = z->huff_ac[th].values; + } + for (i=0; i < n; ++i) + v[i] = stbi__get8(z->s); + if (tc != 0) + stbi__build_fast_ac(z->fast_ac[th], z->huff_ac + th); + L -= n; + } + return L==0; + } + + // check for comment block or APP blocks + if ((m >= 0xE0 && m <= 0xEF) || m == 0xFE) { + L = stbi__get16be(z->s); + if (L < 2) { + if (m == 0xFE) + return stbi__err("bad COM len","Corrupt JPEG"); + else + return stbi__err("bad APP len","Corrupt JPEG"); + } + L -= 2; + + if (m == 0xE0 && L >= 5) { // JFIF APP0 segment + static const unsigned char tag[5] = {'J','F','I','F','\0'}; + int ok = 1; + int i; + for (i=0; i < 5; ++i) + if (stbi__get8(z->s) != tag[i]) + ok = 0; + L -= 5; + if (ok) + z->jfif = 1; + } else if (m == 0xEE && L >= 12) { // Adobe APP14 segment + static const unsigned char tag[6] = {'A','d','o','b','e','\0'}; + int ok = 1; + int i; + for (i=0; i < 6; ++i) + if (stbi__get8(z->s) != tag[i]) + ok = 0; + L -= 6; + if (ok) { + stbi__get8(z->s); // version + stbi__get16be(z->s); // flags0 + stbi__get16be(z->s); // flags1 + z->app14_color_transform = stbi__get8(z->s); // color transform + L -= 6; + } + } + + stbi__skip(z->s, L); + return 1; + } + + return stbi__err("unknown marker","Corrupt JPEG"); +} + +// after we see SOS +static int stbi__process_scan_header(stbi__jpeg *z) +{ + int i; + int Ls = stbi__get16be(z->s); + z->scan_n = stbi__get8(z->s); + if (z->scan_n < 1 || z->scan_n > 4 || z->scan_n > (int) z->s->img_n) return stbi__err("bad SOS component count","Corrupt JPEG"); + if (Ls != 6+2*z->scan_n) return stbi__err("bad SOS len","Corrupt JPEG"); + for (i=0; i < z->scan_n; ++i) { + int id = stbi__get8(z->s), which; + int q = stbi__get8(z->s); + for (which = 0; which < z->s->img_n; ++which) + if (z->img_comp[which].id == id) + break; + if (which == z->s->img_n) return 0; // no match + z->img_comp[which].hd = q >> 4; if (z->img_comp[which].hd > 3) return stbi__err("bad DC huff","Corrupt JPEG"); + z->img_comp[which].ha = q & 15; if (z->img_comp[which].ha > 3) return stbi__err("bad AC huff","Corrupt JPEG"); + z->order[i] = which; + } + + { + int aa; + z->spec_start = stbi__get8(z->s); + z->spec_end = stbi__get8(z->s); // should be 63, but might be 0 + aa = stbi__get8(z->s); + z->succ_high = (aa >> 4); + z->succ_low = (aa & 15); + if (z->progressive) { + if (z->spec_start > 63 || z->spec_end > 63 || z->spec_start > z->spec_end || z->succ_high > 13 || z->succ_low > 13) + return stbi__err("bad SOS", "Corrupt JPEG"); + } else { + if (z->spec_start != 0) return stbi__err("bad SOS","Corrupt JPEG"); + if (z->succ_high != 0 || z->succ_low != 0) return stbi__err("bad SOS","Corrupt JPEG"); + z->spec_end = 63; + } + } + + return 1; +} + +static int stbi__free_jpeg_components(stbi__jpeg *z, int ncomp, int why) +{ + int i; + for (i=0; i < ncomp; ++i) { + if (z->img_comp[i].raw_data) { + STBI_FREE(z->img_comp[i].raw_data); + z->img_comp[i].raw_data = NULL; + z->img_comp[i].data = NULL; + } + if (z->img_comp[i].raw_coeff) { + STBI_FREE(z->img_comp[i].raw_coeff); + z->img_comp[i].raw_coeff = 0; + z->img_comp[i].coeff = 0; + } + if (z->img_comp[i].linebuf) { + STBI_FREE(z->img_comp[i].linebuf); + z->img_comp[i].linebuf = NULL; + } + } + return why; +} + +static int stbi__process_frame_header(stbi__jpeg *z, int scan) +{ + stbi__context *s = z->s; + int Lf,p,i,q, h_max=1,v_max=1,c; + Lf = stbi__get16be(s); if (Lf < 11) return stbi__err("bad SOF len","Corrupt JPEG"); // JPEG + p = stbi__get8(s); if (p != 8) return stbi__err("only 8-bit","JPEG format not supported: 8-bit only"); // JPEG baseline + s->img_y = stbi__get16be(s); if (s->img_y == 0) return stbi__err("no header height", "JPEG format not supported: delayed height"); // Legal, but we don't handle it--but neither does IJG + s->img_x = stbi__get16be(s); if (s->img_x == 0) return stbi__err("0 width","Corrupt JPEG"); // JPEG requires + c = stbi__get8(s); + if (c != 3 && c != 1 && c != 4) return stbi__err("bad component count","Corrupt JPEG"); + s->img_n = c; + for (i=0; i < c; ++i) { + z->img_comp[i].data = NULL; + z->img_comp[i].linebuf = NULL; + } + + if (Lf != 8+3*s->img_n) return stbi__err("bad SOF len","Corrupt JPEG"); + + z->rgb = 0; + for (i=0; i < s->img_n; ++i) { + static const unsigned char rgb[3] = { 'R', 'G', 'B' }; + z->img_comp[i].id = stbi__get8(s); + if (s->img_n == 3 && z->img_comp[i].id == rgb[i]) + ++z->rgb; + q = stbi__get8(s); + z->img_comp[i].h = (q >> 4); if (!z->img_comp[i].h || z->img_comp[i].h > 4) return stbi__err("bad H","Corrupt JPEG"); + z->img_comp[i].v = q & 15; if (!z->img_comp[i].v || z->img_comp[i].v > 4) return stbi__err("bad V","Corrupt JPEG"); + z->img_comp[i].tq = stbi__get8(s); if (z->img_comp[i].tq > 3) return stbi__err("bad TQ","Corrupt JPEG"); + } + + if (scan != STBI__SCAN_load) return 1; + + if (!stbi__mad3sizes_valid(s->img_x, s->img_y, s->img_n, 0)) return stbi__err("too large", "Image too large to decode"); + + for (i=0; i < s->img_n; ++i) { + if (z->img_comp[i].h > h_max) h_max = z->img_comp[i].h; + if (z->img_comp[i].v > v_max) v_max = z->img_comp[i].v; + } + + // compute interleaved mcu info + z->img_h_max = h_max; + z->img_v_max = v_max; + z->img_mcu_w = h_max * 8; + z->img_mcu_h = v_max * 8; + // these sizes can't be more than 17 bits + z->img_mcu_x = (s->img_x + z->img_mcu_w-1) / z->img_mcu_w; + z->img_mcu_y = (s->img_y + z->img_mcu_h-1) / z->img_mcu_h; + + for (i=0; i < s->img_n; ++i) { + // number of effective pixels (e.g. for non-interleaved MCU) + z->img_comp[i].x = (s->img_x * z->img_comp[i].h + h_max-1) / h_max; + z->img_comp[i].y = (s->img_y * z->img_comp[i].v + v_max-1) / v_max; + // to simplify generation, we'll allocate enough memory to decode + // the bogus oversized data from using interleaved MCUs and their + // big blocks (e.g. a 16x16 iMCU on an image of width 33); we won't + // discard the extra data until colorspace conversion + // + // img_mcu_x, img_mcu_y: <=17 bits; comp[i].h and .v are <=4 (checked earlier) + // so these muls can't overflow with 32-bit ints (which we require) + z->img_comp[i].w2 = z->img_mcu_x * z->img_comp[i].h * 8; + z->img_comp[i].h2 = z->img_mcu_y * z->img_comp[i].v * 8; + z->img_comp[i].coeff = 0; + z->img_comp[i].raw_coeff = 0; + z->img_comp[i].linebuf = NULL; + z->img_comp[i].raw_data = stbi__malloc_mad2(z->img_comp[i].w2, z->img_comp[i].h2, 15); + if (z->img_comp[i].raw_data == NULL) + return stbi__free_jpeg_components(z, i+1, stbi__err("outofmem", "Out of memory")); + // align blocks for idct using mmx/sse + z->img_comp[i].data = (stbi_uc*) (((size_t) z->img_comp[i].raw_data + 15) & ~15); + if (z->progressive) { + // w2, h2 are multiples of 8 (see above) + z->img_comp[i].coeff_w = z->img_comp[i].w2 / 8; + z->img_comp[i].coeff_h = z->img_comp[i].h2 / 8; + z->img_comp[i].raw_coeff = stbi__malloc_mad3(z->img_comp[i].w2, z->img_comp[i].h2, sizeof(short), 15); + if (z->img_comp[i].raw_coeff == NULL) + return stbi__free_jpeg_components(z, i+1, stbi__err("outofmem", "Out of memory")); + z->img_comp[i].coeff = (short*) (((size_t) z->img_comp[i].raw_coeff + 15) & ~15); + } + } + + return 1; +} + +// use comparisons since in some cases we handle more than one case (e.g. SOF) +#define stbi__DNL(x) ((x) == 0xdc) +#define stbi__SOI(x) ((x) == 0xd8) +#define stbi__EOI(x) ((x) == 0xd9) +#define stbi__SOF(x) ((x) == 0xc0 || (x) == 0xc1 || (x) == 0xc2) +#define stbi__SOS(x) ((x) == 0xda) + +#define stbi__SOF_progressive(x) ((x) == 0xc2) + +static int stbi__decode_jpeg_header(stbi__jpeg *z, int scan) +{ + int m; + z->jfif = 0; + z->app14_color_transform = -1; // valid values are 0,1,2 + z->marker = STBI__MARKER_none; // initialize cached marker to empty + m = stbi__get_marker(z); + if (!stbi__SOI(m)) return stbi__err("no SOI","Corrupt JPEG"); + if (scan == STBI__SCAN_type) return 1; + m = stbi__get_marker(z); + while (!stbi__SOF(m)) { + if (!stbi__process_marker(z,m)) return 0; + m = stbi__get_marker(z); + while (m == STBI__MARKER_none) { + // some files have extra padding after their blocks, so ok, we'll scan + if (stbi__at_eof(z->s)) return stbi__err("no SOF", "Corrupt JPEG"); + m = stbi__get_marker(z); + } + } + z->progressive = stbi__SOF_progressive(m); + if (!stbi__process_frame_header(z, scan)) return 0; + return 1; +} + +// decode image to YCbCr format +static int stbi__decode_jpeg_image(stbi__jpeg *j) +{ + int m; + for (m = 0; m < 4; m++) { + j->img_comp[m].raw_data = NULL; + j->img_comp[m].raw_coeff = NULL; + } + j->restart_interval = 0; + if (!stbi__decode_jpeg_header(j, STBI__SCAN_load)) return 0; + m = stbi__get_marker(j); + while (!stbi__EOI(m)) { + if (stbi__SOS(m)) { + if (!stbi__process_scan_header(j)) return 0; + if (!stbi__parse_entropy_coded_data(j)) return 0; + if (j->marker == STBI__MARKER_none ) { + // handle 0s at the end of image data from IP Kamera 9060 + while (!stbi__at_eof(j->s)) { + int x = stbi__get8(j->s); + if (x == 255) { + j->marker = stbi__get8(j->s); + break; + } + } + // if we reach eof without hitting a marker, stbi__get_marker() below will fail and we'll eventually return 0 + } + } else if (stbi__DNL(m)) { + int Ld = stbi__get16be(j->s); + stbi__uint32 NL = stbi__get16be(j->s); + if (Ld != 4) return stbi__err("bad DNL len", "Corrupt JPEG"); + if (NL != j->s->img_y) return stbi__err("bad DNL height", "Corrupt JPEG"); + } else { + if (!stbi__process_marker(j, m)) return 0; + } + m = stbi__get_marker(j); + } + if (j->progressive) + stbi__jpeg_finish(j); + return 1; +} + +// static jfif-centered resampling (across block boundaries) + +typedef stbi_uc *(*resample_row_func)(stbi_uc *out, stbi_uc *in0, stbi_uc *in1, + int w, int hs); + +#define stbi__div4(x) ((stbi_uc) ((x) >> 2)) + +static stbi_uc *resample_row_1(stbi_uc *out, stbi_uc *in_near, stbi_uc *in_far, int w, int hs) +{ + STBI_NOTUSED(out); + STBI_NOTUSED(in_far); + STBI_NOTUSED(w); + STBI_NOTUSED(hs); + return in_near; +} + +static stbi_uc* stbi__resample_row_v_2(stbi_uc *out, stbi_uc *in_near, stbi_uc *in_far, int w, int hs) +{ + // need to generate two samples vertically for every one in input + int i; + STBI_NOTUSED(hs); + for (i=0; i < w; ++i) + out[i] = stbi__div4(3*in_near[i] + in_far[i] + 2); + return out; +} + +static stbi_uc* stbi__resample_row_h_2(stbi_uc *out, stbi_uc *in_near, stbi_uc *in_far, int w, int hs) +{ + // need to generate two samples horizontally for every one in input + int i; + stbi_uc *input = in_near; + + if (w == 1) { + // if only one sample, can't do any interpolation + out[0] = out[1] = input[0]; + return out; + } + + out[0] = input[0]; + out[1] = stbi__div4(input[0]*3 + input[1] + 2); + for (i=1; i < w-1; ++i) { + int n = 3*input[i]+2; + out[i*2+0] = stbi__div4(n+input[i-1]); + out[i*2+1] = stbi__div4(n+input[i+1]); + } + out[i*2+0] = stbi__div4(input[w-2]*3 + input[w-1] + 2); + out[i*2+1] = input[w-1]; + + STBI_NOTUSED(in_far); + STBI_NOTUSED(hs); + + return out; +} + +#define stbi__div16(x) ((stbi_uc) ((x) >> 4)) + +static stbi_uc *stbi__resample_row_hv_2(stbi_uc *out, stbi_uc *in_near, stbi_uc *in_far, int w, int hs) +{ + // need to generate 2x2 samples for every one in input + int i,t0,t1; + if (w == 1) { + out[0] = out[1] = stbi__div4(3*in_near[0] + in_far[0] + 2); + return out; + } + + t1 = 3*in_near[0] + in_far[0]; + out[0] = stbi__div4(t1+2); + for (i=1; i < w; ++i) { + t0 = t1; + t1 = 3*in_near[i]+in_far[i]; + out[i*2-1] = stbi__div16(3*t0 + t1 + 8); + out[i*2 ] = stbi__div16(3*t1 + t0 + 8); + } + out[w*2-1] = stbi__div4(t1+2); + + STBI_NOTUSED(hs); + + return out; +} + +#if defined(STBI_SSE2) || defined(STBI_NEON) +static stbi_uc *stbi__resample_row_hv_2_simd(stbi_uc *out, stbi_uc *in_near, stbi_uc *in_far, int w, int hs) +{ + // need to generate 2x2 samples for every one in input + int i=0,t0,t1; + + if (w == 1) { + out[0] = out[1] = stbi__div4(3*in_near[0] + in_far[0] + 2); + return out; + } + + t1 = 3*in_near[0] + in_far[0]; + // process groups of 8 pixels for as long as we can. + // note we can't handle the last pixel in a row in this loop + // because we need to handle the filter boundary conditions. + for (; i < ((w-1) & ~7); i += 8) { +#if defined(STBI_SSE2) + // load and perform the vertical filtering pass + // this uses 3*x + y = 4*x + (y - x) + __m128i zero = _mm_setzero_si128(); + __m128i farb = _mm_loadl_epi64((__m128i *) (in_far + i)); + __m128i nearb = _mm_loadl_epi64((__m128i *) (in_near + i)); + __m128i farw = _mm_unpacklo_epi8(farb, zero); + __m128i nearw = _mm_unpacklo_epi8(nearb, zero); + __m128i diff = _mm_sub_epi16(farw, nearw); + __m128i nears = _mm_slli_epi16(nearw, 2); + __m128i curr = _mm_add_epi16(nears, diff); // current row + + // horizontal filter works the same based on shifted vers of current + // row. "prev" is current row shifted right by 1 pixel; we need to + // insert the previous pixel value (from t1). + // "next" is current row shifted left by 1 pixel, with first pixel + // of next block of 8 pixels added in. + __m128i prv0 = _mm_slli_si128(curr, 2); + __m128i nxt0 = _mm_srli_si128(curr, 2); + __m128i prev = _mm_insert_epi16(prv0, t1, 0); + __m128i next = _mm_insert_epi16(nxt0, 3*in_near[i+8] + in_far[i+8], 7); + + // horizontal filter, polyphase implementation since it's convenient: + // even pixels = 3*cur + prev = cur*4 + (prev - cur) + // odd pixels = 3*cur + next = cur*4 + (next - cur) + // note the shared term. + __m128i bias = _mm_set1_epi16(8); + __m128i curs = _mm_slli_epi16(curr, 2); + __m128i prvd = _mm_sub_epi16(prev, curr); + __m128i nxtd = _mm_sub_epi16(next, curr); + __m128i curb = _mm_add_epi16(curs, bias); + __m128i even = _mm_add_epi16(prvd, curb); + __m128i odd = _mm_add_epi16(nxtd, curb); + + // interleave even and odd pixels, then undo scaling. + __m128i int0 = _mm_unpacklo_epi16(even, odd); + __m128i int1 = _mm_unpackhi_epi16(even, odd); + __m128i de0 = _mm_srli_epi16(int0, 4); + __m128i de1 = _mm_srli_epi16(int1, 4); + + // pack and write output + __m128i outv = _mm_packus_epi16(de0, de1); + _mm_storeu_si128((__m128i *) (out + i*2), outv); +#elif defined(STBI_NEON) + // load and perform the vertical filtering pass + // this uses 3*x + y = 4*x + (y - x) + uint8x8_t farb = vld1_u8(in_far + i); + uint8x8_t nearb = vld1_u8(in_near + i); + int16x8_t diff = vreinterpretq_s16_u16(vsubl_u8(farb, nearb)); + int16x8_t nears = vreinterpretq_s16_u16(vshll_n_u8(nearb, 2)); + int16x8_t curr = vaddq_s16(nears, diff); // current row + + // horizontal filter works the same based on shifted vers of current + // row. "prev" is current row shifted right by 1 pixel; we need to + // insert the previous pixel value (from t1). + // "next" is current row shifted left by 1 pixel, with first pixel + // of next block of 8 pixels added in. + int16x8_t prv0 = vextq_s16(curr, curr, 7); + int16x8_t nxt0 = vextq_s16(curr, curr, 1); + int16x8_t prev = vsetq_lane_s16(t1, prv0, 0); + int16x8_t next = vsetq_lane_s16(3*in_near[i+8] + in_far[i+8], nxt0, 7); + + // horizontal filter, polyphase implementation since it's convenient: + // even pixels = 3*cur + prev = cur*4 + (prev - cur) + // odd pixels = 3*cur + next = cur*4 + (next - cur) + // note the shared term. + int16x8_t curs = vshlq_n_s16(curr, 2); + int16x8_t prvd = vsubq_s16(prev, curr); + int16x8_t nxtd = vsubq_s16(next, curr); + int16x8_t even = vaddq_s16(curs, prvd); + int16x8_t odd = vaddq_s16(curs, nxtd); + + // undo scaling and round, then store with even/odd phases interleaved + uint8x8x2_t o; + o.val[0] = vqrshrun_n_s16(even, 4); + o.val[1] = vqrshrun_n_s16(odd, 4); + vst2_u8(out + i*2, o); +#endif + + // "previous" value for next iter + t1 = 3*in_near[i+7] + in_far[i+7]; + } + + t0 = t1; + t1 = 3*in_near[i] + in_far[i]; + out[i*2] = stbi__div16(3*t1 + t0 + 8); + + for (++i; i < w; ++i) { + t0 = t1; + t1 = 3*in_near[i]+in_far[i]; + out[i*2-1] = stbi__div16(3*t0 + t1 + 8); + out[i*2 ] = stbi__div16(3*t1 + t0 + 8); + } + out[w*2-1] = stbi__div4(t1+2); + + STBI_NOTUSED(hs); + + return out; +} +#endif + +static stbi_uc *stbi__resample_row_generic(stbi_uc *out, stbi_uc *in_near, stbi_uc *in_far, int w, int hs) +{ + // resample with nearest-neighbor + int i,j; + STBI_NOTUSED(in_far); + for (i=0; i < w; ++i) + for (j=0; j < hs; ++j) + out[i*hs+j] = in_near[i]; + return out; +} + +// this is a reduced-precision calculation of YCbCr-to-RGB introduced +// to make sure the code produces the same results in both SIMD and scalar +#define stbi__float2fixed(x) (((int) ((x) * 4096.0f + 0.5f)) << 8) +static void stbi__YCbCr_to_RGB_row(stbi_uc *out, const stbi_uc *y, const stbi_uc *pcb, const stbi_uc *pcr, int count, int step) +{ + int i; + for (i=0; i < count; ++i) { + int y_fixed = (y[i] << 20) + (1<<19); // rounding + int r,g,b; + int cr = pcr[i] - 128; + int cb = pcb[i] - 128; + r = y_fixed + cr* stbi__float2fixed(1.40200f); + g = y_fixed + (cr*-stbi__float2fixed(0.71414f)) + ((cb*-stbi__float2fixed(0.34414f)) & 0xffff0000); + b = y_fixed + cb* stbi__float2fixed(1.77200f); + r >>= 20; + g >>= 20; + b >>= 20; + if ((unsigned) r > 255) { if (r < 0) r = 0; else r = 255; } + if ((unsigned) g > 255) { if (g < 0) g = 0; else g = 255; } + if ((unsigned) b > 255) { if (b < 0) b = 0; else b = 255; } + out[0] = (stbi_uc)r; + out[1] = (stbi_uc)g; + out[2] = (stbi_uc)b; + out[3] = 255; + out += step; + } +} + +#if defined(STBI_SSE2) || defined(STBI_NEON) +static void stbi__YCbCr_to_RGB_simd(stbi_uc *out, stbi_uc const *y, stbi_uc const *pcb, stbi_uc const *pcr, int count, int step) +{ + int i = 0; + +#ifdef STBI_SSE2 + // step == 3 is pretty ugly on the final interleave, and i'm not convinced + // it's useful in practice (you wouldn't use it for textures, for example). + // so just accelerate step == 4 case. + if (step == 4) { + // this is a fairly straightforward implementation and not super-optimized. + __m128i signflip = _mm_set1_epi8(-0x80); + __m128i cr_const0 = _mm_set1_epi16( (short) ( 1.40200f*4096.0f+0.5f)); + __m128i cr_const1 = _mm_set1_epi16( - (short) ( 0.71414f*4096.0f+0.5f)); + __m128i cb_const0 = _mm_set1_epi16( - (short) ( 0.34414f*4096.0f+0.5f)); + __m128i cb_const1 = _mm_set1_epi16( (short) ( 1.77200f*4096.0f+0.5f)); + __m128i y_bias = _mm_set1_epi8((char) (unsigned char) 128); + __m128i xw = _mm_set1_epi16(255); // alpha channel + + for (; i+7 < count; i += 8) { + // load + __m128i y_bytes = _mm_loadl_epi64((__m128i *) (y+i)); + __m128i cr_bytes = _mm_loadl_epi64((__m128i *) (pcr+i)); + __m128i cb_bytes = _mm_loadl_epi64((__m128i *) (pcb+i)); + __m128i cr_biased = _mm_xor_si128(cr_bytes, signflip); // -128 + __m128i cb_biased = _mm_xor_si128(cb_bytes, signflip); // -128 + + // unpack to short (and left-shift cr, cb by 8) + __m128i yw = _mm_unpacklo_epi8(y_bias, y_bytes); + __m128i crw = _mm_unpacklo_epi8(_mm_setzero_si128(), cr_biased); + __m128i cbw = _mm_unpacklo_epi8(_mm_setzero_si128(), cb_biased); + + // color transform + __m128i yws = _mm_srli_epi16(yw, 4); + __m128i cr0 = _mm_mulhi_epi16(cr_const0, crw); + __m128i cb0 = _mm_mulhi_epi16(cb_const0, cbw); + __m128i cb1 = _mm_mulhi_epi16(cbw, cb_const1); + __m128i cr1 = _mm_mulhi_epi16(crw, cr_const1); + __m128i rws = _mm_add_epi16(cr0, yws); + __m128i gwt = _mm_add_epi16(cb0, yws); + __m128i bws = _mm_add_epi16(yws, cb1); + __m128i gws = _mm_add_epi16(gwt, cr1); + + // descale + __m128i rw = _mm_srai_epi16(rws, 4); + __m128i bw = _mm_srai_epi16(bws, 4); + __m128i gw = _mm_srai_epi16(gws, 4); + + // back to byte, set up for transpose + __m128i brb = _mm_packus_epi16(rw, bw); + __m128i gxb = _mm_packus_epi16(gw, xw); + + // transpose to interleave channels + __m128i t0 = _mm_unpacklo_epi8(brb, gxb); + __m128i t1 = _mm_unpackhi_epi8(brb, gxb); + __m128i o0 = _mm_unpacklo_epi16(t0, t1); + __m128i o1 = _mm_unpackhi_epi16(t0, t1); + + // store + _mm_storeu_si128((__m128i *) (out + 0), o0); + _mm_storeu_si128((__m128i *) (out + 16), o1); + out += 32; + } + } +#endif + +#ifdef STBI_NEON + // in this version, step=3 support would be easy to add. but is there demand? + if (step == 4) { + // this is a fairly straightforward implementation and not super-optimized. + uint8x8_t signflip = vdup_n_u8(0x80); + int16x8_t cr_const0 = vdupq_n_s16( (short) ( 1.40200f*4096.0f+0.5f)); + int16x8_t cr_const1 = vdupq_n_s16( - (short) ( 0.71414f*4096.0f+0.5f)); + int16x8_t cb_const0 = vdupq_n_s16( - (short) ( 0.34414f*4096.0f+0.5f)); + int16x8_t cb_const1 = vdupq_n_s16( (short) ( 1.77200f*4096.0f+0.5f)); + + for (; i+7 < count; i += 8) { + // load + uint8x8_t y_bytes = vld1_u8(y + i); + uint8x8_t cr_bytes = vld1_u8(pcr + i); + uint8x8_t cb_bytes = vld1_u8(pcb + i); + int8x8_t cr_biased = vreinterpret_s8_u8(vsub_u8(cr_bytes, signflip)); + int8x8_t cb_biased = vreinterpret_s8_u8(vsub_u8(cb_bytes, signflip)); + + // expand to s16 + int16x8_t yws = vreinterpretq_s16_u16(vshll_n_u8(y_bytes, 4)); + int16x8_t crw = vshll_n_s8(cr_biased, 7); + int16x8_t cbw = vshll_n_s8(cb_biased, 7); + + // color transform + int16x8_t cr0 = vqdmulhq_s16(crw, cr_const0); + int16x8_t cb0 = vqdmulhq_s16(cbw, cb_const0); + int16x8_t cr1 = vqdmulhq_s16(crw, cr_const1); + int16x8_t cb1 = vqdmulhq_s16(cbw, cb_const1); + int16x8_t rws = vaddq_s16(yws, cr0); + int16x8_t gws = vaddq_s16(vaddq_s16(yws, cb0), cr1); + int16x8_t bws = vaddq_s16(yws, cb1); + + // undo scaling, round, convert to byte + uint8x8x4_t o; + o.val[0] = vqrshrun_n_s16(rws, 4); + o.val[1] = vqrshrun_n_s16(gws, 4); + o.val[2] = vqrshrun_n_s16(bws, 4); + o.val[3] = vdup_n_u8(255); + + // store, interleaving r/g/b/a + vst4_u8(out, o); + out += 8*4; + } + } +#endif + + for (; i < count; ++i) { + int y_fixed = (y[i] << 20) + (1<<19); // rounding + int r,g,b; + int cr = pcr[i] - 128; + int cb = pcb[i] - 128; + r = y_fixed + cr* stbi__float2fixed(1.40200f); + g = y_fixed + cr*-stbi__float2fixed(0.71414f) + ((cb*-stbi__float2fixed(0.34414f)) & 0xffff0000); + b = y_fixed + cb* stbi__float2fixed(1.77200f); + r >>= 20; + g >>= 20; + b >>= 20; + if ((unsigned) r > 255) { if (r < 0) r = 0; else r = 255; } + if ((unsigned) g > 255) { if (g < 0) g = 0; else g = 255; } + if ((unsigned) b > 255) { if (b < 0) b = 0; else b = 255; } + out[0] = (stbi_uc)r; + out[1] = (stbi_uc)g; + out[2] = (stbi_uc)b; + out[3] = 255; + out += step; + } +} +#endif + +// set up the kernels +static void stbi__setup_jpeg(stbi__jpeg *j) +{ + j->idct_block_kernel = stbi__idct_block; + j->YCbCr_to_RGB_kernel = stbi__YCbCr_to_RGB_row; + j->resample_row_hv_2_kernel = stbi__resample_row_hv_2; + +#ifdef STBI_SSE2 + if (stbi__sse2_available()) { + j->idct_block_kernel = stbi__idct_simd; + j->YCbCr_to_RGB_kernel = stbi__YCbCr_to_RGB_simd; + j->resample_row_hv_2_kernel = stbi__resample_row_hv_2_simd; + } +#endif + +#ifdef STBI_NEON + j->idct_block_kernel = stbi__idct_simd; + j->YCbCr_to_RGB_kernel = stbi__YCbCr_to_RGB_simd; + j->resample_row_hv_2_kernel = stbi__resample_row_hv_2_simd; +#endif +} + +// clean up the temporary component buffers +static void stbi__cleanup_jpeg(stbi__jpeg *j) +{ + stbi__free_jpeg_components(j, j->s->img_n, 0); +} + +typedef struct +{ + resample_row_func resample; + stbi_uc *line0,*line1; + int hs,vs; // expansion factor in each axis + int w_lores; // horizontal pixels pre-expansion + int ystep; // how far through vertical expansion we are + int ypos; // which pre-expansion row we're on +} stbi__resample; + +// fast 0..255 * 0..255 => 0..255 rounded multiplication +static stbi_uc stbi__blinn_8x8(stbi_uc x, stbi_uc y) +{ + unsigned int t = x*y + 128; + return (stbi_uc) ((t + (t >>8)) >> 8); +} + +static stbi_uc *load_jpeg_image(stbi__jpeg *z, int *out_x, int *out_y, int *comp, int req_comp) +{ + int n, decode_n, is_rgb; + z->s->img_n = 0; // make stbi__cleanup_jpeg safe + + // validate req_comp + if (req_comp < 0 || req_comp > 4) return stbi__errpuc("bad req_comp", "Internal error"); + + // load a jpeg image from whichever source, but leave in YCbCr format + if (!stbi__decode_jpeg_image(z)) { stbi__cleanup_jpeg(z); return NULL; } + + // determine actual number of components to generate + n = req_comp ? req_comp : z->s->img_n >= 3 ? 3 : 1; + + is_rgb = z->s->img_n == 3 && (z->rgb == 3 || (z->app14_color_transform == 0 && !z->jfif)); + + if (z->s->img_n == 3 && n < 3 && !is_rgb) + decode_n = 1; + else + decode_n = z->s->img_n; + + // resample and color-convert + { + int k; + unsigned int i,j; + stbi_uc *output; + stbi_uc *coutput[4] = { NULL, NULL, NULL, NULL }; + + stbi__resample res_comp[4]; + + for (k=0; k < decode_n; ++k) { + stbi__resample *r = &res_comp[k]; + + // allocate line buffer big enough for upsampling off the edges + // with upsample factor of 4 + z->img_comp[k].linebuf = (stbi_uc *) stbi__malloc(z->s->img_x + 3); + if (!z->img_comp[k].linebuf) { stbi__cleanup_jpeg(z); return stbi__errpuc("outofmem", "Out of memory"); } + + r->hs = z->img_h_max / z->img_comp[k].h; + r->vs = z->img_v_max / z->img_comp[k].v; + r->ystep = r->vs >> 1; + r->w_lores = (z->s->img_x + r->hs-1) / r->hs; + r->ypos = 0; + r->line0 = r->line1 = z->img_comp[k].data; + + if (r->hs == 1 && r->vs == 1) r->resample = resample_row_1; + else if (r->hs == 1 && r->vs == 2) r->resample = stbi__resample_row_v_2; + else if (r->hs == 2 && r->vs == 1) r->resample = stbi__resample_row_h_2; + else if (r->hs == 2 && r->vs == 2) r->resample = z->resample_row_hv_2_kernel; + else r->resample = stbi__resample_row_generic; + } + + // can't error after this so, this is safe + output = (stbi_uc *) stbi__malloc_mad3(n, z->s->img_x, z->s->img_y, 1); + if (!output) { stbi__cleanup_jpeg(z); return stbi__errpuc("outofmem", "Out of memory"); } + + // now go ahead and resample + for (j=0; j < z->s->img_y; ++j) { + stbi_uc *out = output + n * z->s->img_x * j; + for (k=0; k < decode_n; ++k) { + stbi__resample *r = &res_comp[k]; + int y_bot = r->ystep >= (r->vs >> 1); + coutput[k] = r->resample(z->img_comp[k].linebuf, + y_bot ? r->line1 : r->line0, + y_bot ? r->line0 : r->line1, + r->w_lores, r->hs); + if (++r->ystep >= r->vs) { + r->ystep = 0; + r->line0 = r->line1; + if (++r->ypos < z->img_comp[k].y) + r->line1 += z->img_comp[k].w2; + } + } + if (n >= 3) { + stbi_uc *y = coutput[0]; + if (z->s->img_n == 3) { + if (is_rgb) { + for (i=0; i < z->s->img_x; ++i) { + out[0] = y[i]; + out[1] = coutput[1][i]; + out[2] = coutput[2][i]; + out[3] = 255; + out += n; + } + } else { + z->YCbCr_to_RGB_kernel(out, y, coutput[1], coutput[2], z->s->img_x, n); + } + } else if (z->s->img_n == 4) { + if (z->app14_color_transform == 0) { // CMYK + for (i=0; i < z->s->img_x; ++i) { + stbi_uc m = coutput[3][i]; + out[0] = stbi__blinn_8x8(coutput[0][i], m); + out[1] = stbi__blinn_8x8(coutput[1][i], m); + out[2] = stbi__blinn_8x8(coutput[2][i], m); + out[3] = 255; + out += n; + } + } else if (z->app14_color_transform == 2) { // YCCK + z->YCbCr_to_RGB_kernel(out, y, coutput[1], coutput[2], z->s->img_x, n); + for (i=0; i < z->s->img_x; ++i) { + stbi_uc m = coutput[3][i]; + out[0] = stbi__blinn_8x8(255 - out[0], m); + out[1] = stbi__blinn_8x8(255 - out[1], m); + out[2] = stbi__blinn_8x8(255 - out[2], m); + out += n; + } + } else { // YCbCr + alpha? Ignore the fourth channel for now + z->YCbCr_to_RGB_kernel(out, y, coutput[1], coutput[2], z->s->img_x, n); + } + } else + for (i=0; i < z->s->img_x; ++i) { + out[0] = out[1] = out[2] = y[i]; + out[3] = 255; // not used if n==3 + out += n; + } + } else { + if (is_rgb) { + if (n == 1) + for (i=0; i < z->s->img_x; ++i) + *out++ = stbi__compute_y(coutput[0][i], coutput[1][i], coutput[2][i]); + else { + for (i=0; i < z->s->img_x; ++i, out += 2) { + out[0] = stbi__compute_y(coutput[0][i], coutput[1][i], coutput[2][i]); + out[1] = 255; + } + } + } else if (z->s->img_n == 4 && z->app14_color_transform == 0) { + for (i=0; i < z->s->img_x; ++i) { + stbi_uc m = coutput[3][i]; + stbi_uc r = stbi__blinn_8x8(coutput[0][i], m); + stbi_uc g = stbi__blinn_8x8(coutput[1][i], m); + stbi_uc b = stbi__blinn_8x8(coutput[2][i], m); + out[0] = stbi__compute_y(r, g, b); + out[1] = 255; + out += n; + } + } else if (z->s->img_n == 4 && z->app14_color_transform == 2) { + for (i=0; i < z->s->img_x; ++i) { + out[0] = stbi__blinn_8x8(255 - coutput[0][i], coutput[3][i]); + out[1] = 255; + out += n; + } + } else { + stbi_uc *y = coutput[0]; + if (n == 1) + for (i=0; i < z->s->img_x; ++i) out[i] = y[i]; + else + for (i=0; i < z->s->img_x; ++i) { *out++ = y[i]; *out++ = 255; } + } + } + } + stbi__cleanup_jpeg(z); + *out_x = z->s->img_x; + *out_y = z->s->img_y; + if (comp) *comp = z->s->img_n >= 3 ? 3 : 1; // report original components, not output + return output; + } +} + +static void *stbi__jpeg_load(stbi__context *s, int *x, int *y, int *comp, int req_comp, stbi__result_info *ri) +{ + unsigned char* result; + stbi__jpeg* j = (stbi__jpeg*) stbi__malloc(sizeof(stbi__jpeg)); + STBI_NOTUSED(ri); + j->s = s; + stbi__setup_jpeg(j); + result = load_jpeg_image(j, x,y,comp,req_comp); + STBI_FREE(j); + return result; +} + +static int stbi__jpeg_test(stbi__context *s) +{ + int r; + stbi__jpeg* j = (stbi__jpeg*)stbi__malloc(sizeof(stbi__jpeg)); + j->s = s; + stbi__setup_jpeg(j); + r = stbi__decode_jpeg_header(j, STBI__SCAN_type); + stbi__rewind(s); + STBI_FREE(j); + return r; +} + +static int stbi__jpeg_info_raw(stbi__jpeg *j, int *x, int *y, int *comp) +{ + if (!stbi__decode_jpeg_header(j, STBI__SCAN_header)) { + stbi__rewind( j->s ); + return 0; + } + if (x) *x = j->s->img_x; + if (y) *y = j->s->img_y; + if (comp) *comp = j->s->img_n >= 3 ? 3 : 1; + return 1; +} + +static int stbi__jpeg_info(stbi__context *s, int *x, int *y, int *comp) +{ + int result; + stbi__jpeg* j = (stbi__jpeg*) (stbi__malloc(sizeof(stbi__jpeg))); + j->s = s; + result = stbi__jpeg_info_raw(j, x, y, comp); + STBI_FREE(j); + return result; +} +#endif + +// public domain zlib decode v0.2 Sean Barrett 2006-11-18 +// simple implementation +// - all input must be provided in an upfront buffer +// - all output is written to a single output buffer (can malloc/realloc) +// performance +// - fast huffman + +#ifndef STBI_NO_ZLIB + +// fast-way is faster to check than jpeg huffman, but slow way is slower +#define STBI__ZFAST_BITS 9 // accelerate all cases in default tables +#define STBI__ZFAST_MASK ((1 << STBI__ZFAST_BITS) - 1) + +// zlib-style huffman encoding +// (jpegs packs from left, zlib from right, so can't share code) +typedef struct +{ + stbi__uint16 fast[1 << STBI__ZFAST_BITS]; + stbi__uint16 firstcode[16]; + int maxcode[17]; + stbi__uint16 firstsymbol[16]; + stbi_uc size[288]; + stbi__uint16 value[288]; +} stbi__zhuffman; + +stbi_inline static int stbi__bitreverse16(int n) +{ + n = ((n & 0xAAAA) >> 1) | ((n & 0x5555) << 1); + n = ((n & 0xCCCC) >> 2) | ((n & 0x3333) << 2); + n = ((n & 0xF0F0) >> 4) | ((n & 0x0F0F) << 4); + n = ((n & 0xFF00) >> 8) | ((n & 0x00FF) << 8); + return n; +} + +stbi_inline static int stbi__bit_reverse(int v, int bits) +{ + STBI_ASSERT(bits <= 16); + // to bit reverse n bits, reverse 16 and shift + // e.g. 11 bits, bit reverse and shift away 5 + return stbi__bitreverse16(v) >> (16-bits); +} + +static int stbi__zbuild_huffman(stbi__zhuffman *z, const stbi_uc *sizelist, int num) +{ + int i,k=0; + int code, next_code[16], sizes[17]; + + // DEFLATE spec for generating codes + memset(sizes, 0, sizeof(sizes)); + memset(z->fast, 0, sizeof(z->fast)); + for (i=0; i < num; ++i) + ++sizes[sizelist[i]]; + sizes[0] = 0; + for (i=1; i < 16; ++i) + if (sizes[i] > (1 << i)) + return stbi__err("bad sizes", "Corrupt PNG"); + code = 0; + for (i=1; i < 16; ++i) { + next_code[i] = code; + z->firstcode[i] = (stbi__uint16) code; + z->firstsymbol[i] = (stbi__uint16) k; + code = (code + sizes[i]); + if (sizes[i]) + if (code-1 >= (1 << i)) return stbi__err("bad codelengths","Corrupt PNG"); + z->maxcode[i] = code << (16-i); // preshift for inner loop + code <<= 1; + k += sizes[i]; + } + z->maxcode[16] = 0x10000; // sentinel + for (i=0; i < num; ++i) { + int s = sizelist[i]; + if (s) { + int c = next_code[s] - z->firstcode[s] + z->firstsymbol[s]; + stbi__uint16 fastv = (stbi__uint16) ((s << 9) | i); + z->size [c] = (stbi_uc ) s; + z->value[c] = (stbi__uint16) i; + if (s <= STBI__ZFAST_BITS) { + int j = stbi__bit_reverse(next_code[s],s); + while (j < (1 << STBI__ZFAST_BITS)) { + z->fast[j] = fastv; + j += (1 << s); + } + } + ++next_code[s]; + } + } + return 1; +} + +// zlib-from-memory implementation for PNG reading +// because PNG allows splitting the zlib stream arbitrarily, +// and it's annoying structurally to have PNG call ZLIB call PNG, +// we require PNG read all the IDATs and combine them into a single +// memory buffer + +typedef struct +{ + stbi_uc *zbuffer, *zbuffer_end; + int num_bits; + stbi__uint32 code_buffer; + + char *zout; + char *zout_start; + char *zout_end; + int z_expandable; + + stbi__zhuffman z_length, z_distance; +} stbi__zbuf; + +stbi_inline static stbi_uc stbi__zget8(stbi__zbuf *z) +{ + if (z->zbuffer >= z->zbuffer_end) return 0; + return *z->zbuffer++; +} + +static void stbi__fill_bits(stbi__zbuf *z) +{ + do { + STBI_ASSERT(z->code_buffer < (1U << z->num_bits)); + z->code_buffer |= (unsigned int) stbi__zget8(z) << z->num_bits; + z->num_bits += 8; + } while (z->num_bits <= 24); +} + +stbi_inline static unsigned int stbi__zreceive(stbi__zbuf *z, int n) +{ + unsigned int k; + if (z->num_bits < n) stbi__fill_bits(z); + k = z->code_buffer & ((1 << n) - 1); + z->code_buffer >>= n; + z->num_bits -= n; + return k; +} + +static int stbi__zhuffman_decode_slowpath(stbi__zbuf *a, stbi__zhuffman *z) +{ + int b,s,k; + // not resolved by fast table, so compute it the slow way + // use jpeg approach, which requires MSbits at top + k = stbi__bit_reverse(a->code_buffer, 16); + for (s=STBI__ZFAST_BITS+1; ; ++s) + if (k < z->maxcode[s]) + break; + if (s == 16) return -1; // invalid code! + // code size is s, so: + b = (k >> (16-s)) - z->firstcode[s] + z->firstsymbol[s]; + STBI_ASSERT(z->size[b] == s); + a->code_buffer >>= s; + a->num_bits -= s; + return z->value[b]; +} + +stbi_inline static int stbi__zhuffman_decode(stbi__zbuf *a, stbi__zhuffman *z) +{ + int b,s; + if (a->num_bits < 16) stbi__fill_bits(a); + b = z->fast[a->code_buffer & STBI__ZFAST_MASK]; + if (b) { + s = b >> 9; + a->code_buffer >>= s; + a->num_bits -= s; + return b & 511; + } + return stbi__zhuffman_decode_slowpath(a, z); +} + +static int stbi__zexpand(stbi__zbuf *z, char *zout, int n) // need to make room for n bytes +{ + char *q; + int cur, limit, old_limit; + z->zout = zout; + if (!z->z_expandable) return stbi__err("output buffer limit","Corrupt PNG"); + cur = (int) (z->zout - z->zout_start); + limit = old_limit = (int) (z->zout_end - z->zout_start); + while (cur + n > limit) + limit *= 2; + q = (char *) STBI_REALLOC_SIZED(z->zout_start, old_limit, limit); + STBI_NOTUSED(old_limit); + if (q == NULL) return stbi__err("outofmem", "Out of memory"); + z->zout_start = q; + z->zout = q + cur; + z->zout_end = q + limit; + return 1; +} + +static const int stbi__zlength_base[31] = { + 3,4,5,6,7,8,9,10,11,13, + 15,17,19,23,27,31,35,43,51,59, + 67,83,99,115,131,163,195,227,258,0,0 }; + +static const int stbi__zlength_extra[31]= +{ 0,0,0,0,0,0,0,0,1,1,1,1,2,2,2,2,3,3,3,3,4,4,4,4,5,5,5,5,0,0,0 }; + +static const int stbi__zdist_base[32] = { 1,2,3,4,5,7,9,13,17,25,33,49,65,97,129,193, +257,385,513,769,1025,1537,2049,3073,4097,6145,8193,12289,16385,24577,0,0}; + +static const int stbi__zdist_extra[32] = +{ 0,0,0,0,1,1,2,2,3,3,4,4,5,5,6,6,7,7,8,8,9,9,10,10,11,11,12,12,13,13}; + +static int stbi__parse_huffman_block(stbi__zbuf *a) +{ + char *zout = a->zout; + for(;;) { + int z = stbi__zhuffman_decode(a, &a->z_length); + if (z < 256) { + if (z < 0) return stbi__err("bad huffman code","Corrupt PNG"); // error in huffman codes + if (zout >= a->zout_end) { + if (!stbi__zexpand(a, zout, 1)) return 0; + zout = a->zout; + } + *zout++ = (char) z; + } else { + stbi_uc *p; + int len,dist; + if (z == 256) { + a->zout = zout; + return 1; + } + z -= 257; + len = stbi__zlength_base[z]; + if (stbi__zlength_extra[z]) len += stbi__zreceive(a, stbi__zlength_extra[z]); + z = stbi__zhuffman_decode(a, &a->z_distance); + if (z < 0) return stbi__err("bad huffman code","Corrupt PNG"); + dist = stbi__zdist_base[z]; + if (stbi__zdist_extra[z]) dist += stbi__zreceive(a, stbi__zdist_extra[z]); + if (zout - a->zout_start < dist) return stbi__err("bad dist","Corrupt PNG"); + if (zout + len > a->zout_end) { + if (!stbi__zexpand(a, zout, len)) return 0; + zout = a->zout; + } + p = (stbi_uc *) (zout - dist); + if (dist == 1) { // run of one byte; common in images. + stbi_uc v = *p; + if (len) { do *zout++ = v; while (--len); } + } else { + if (len) { do *zout++ = *p++; while (--len); } + } + } + } +} + +static int stbi__compute_huffman_codes(stbi__zbuf *a) +{ + static const stbi_uc length_dezigzag[19] = { 16,17,18,0,8,7,9,6,10,5,11,4,12,3,13,2,14,1,15 }; + stbi__zhuffman z_codelength; + stbi_uc lencodes[286+32+137];//padding for maximum single op + stbi_uc codelength_sizes[19]; + int i,n; + + int hlit = stbi__zreceive(a,5) + 257; + int hdist = stbi__zreceive(a,5) + 1; + int hclen = stbi__zreceive(a,4) + 4; + int ntot = hlit + hdist; + + memset(codelength_sizes, 0, sizeof(codelength_sizes)); + for (i=0; i < hclen; ++i) { + int s = stbi__zreceive(a,3); + codelength_sizes[length_dezigzag[i]] = (stbi_uc) s; + } + if (!stbi__zbuild_huffman(&z_codelength, codelength_sizes, 19)) return 0; + + n = 0; + while (n < ntot) { + int c = stbi__zhuffman_decode(a, &z_codelength); + if (c < 0 || c >= 19) return stbi__err("bad codelengths", "Corrupt PNG"); + if (c < 16) + lencodes[n++] = (stbi_uc) c; + else { + stbi_uc fill = 0; + if (c == 16) { + c = stbi__zreceive(a,2)+3; + if (n == 0) return stbi__err("bad codelengths", "Corrupt PNG"); + fill = lencodes[n-1]; + } else if (c == 17) + c = stbi__zreceive(a,3)+3; + else { + STBI_ASSERT(c == 18); + c = stbi__zreceive(a,7)+11; + } + if (ntot - n < c) return stbi__err("bad codelengths", "Corrupt PNG"); + memset(lencodes+n, fill, c); + n += c; + } + } + if (n != ntot) return stbi__err("bad codelengths","Corrupt PNG"); + if (!stbi__zbuild_huffman(&a->z_length, lencodes, hlit)) return 0; + if (!stbi__zbuild_huffman(&a->z_distance, lencodes+hlit, hdist)) return 0; + return 1; +} + +static int stbi__parse_uncompressed_block(stbi__zbuf *a) +{ + stbi_uc header[4]; + int len,nlen,k; + if (a->num_bits & 7) + stbi__zreceive(a, a->num_bits & 7); // discard + // drain the bit-packed data into header + k = 0; + while (a->num_bits > 0) { + header[k++] = (stbi_uc) (a->code_buffer & 255); // suppress MSVC run-time check + a->code_buffer >>= 8; + a->num_bits -= 8; + } + STBI_ASSERT(a->num_bits == 0); + // now fill header the normal way + while (k < 4) + header[k++] = stbi__zget8(a); + len = header[1] * 256 + header[0]; + nlen = header[3] * 256 + header[2]; + if (nlen != (len ^ 0xffff)) return stbi__err("zlib corrupt","Corrupt PNG"); + if (a->zbuffer + len > a->zbuffer_end) return stbi__err("read past buffer","Corrupt PNG"); + if (a->zout + len > a->zout_end) + if (!stbi__zexpand(a, a->zout, len)) return 0; + memcpy(a->zout, a->zbuffer, len); + a->zbuffer += len; + a->zout += len; + return 1; +} + +static int stbi__parse_zlib_header(stbi__zbuf *a) +{ + int cmf = stbi__zget8(a); + int cm = cmf & 15; + /* int cinfo = cmf >> 4; */ + int flg = stbi__zget8(a); + if ((cmf*256+flg) % 31 != 0) return stbi__err("bad zlib header","Corrupt PNG"); // zlib spec + if (flg & 32) return stbi__err("no preset dict","Corrupt PNG"); // preset dictionary not allowed in png + if (cm != 8) return stbi__err("bad compression","Corrupt PNG"); // DEFLATE required for png + // window = 1 << (8 + cinfo)... but who cares, we fully buffer output + return 1; +} + +static const stbi_uc stbi__zdefault_length[288] = +{ + 8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8, 8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8, + 8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8, 8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8, + 8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8, 8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8, + 8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8, 8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8, + 8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8, 9,9,9,9,9,9,9,9,9,9,9,9,9,9,9,9, + 9,9,9,9,9,9,9,9,9,9,9,9,9,9,9,9, 9,9,9,9,9,9,9,9,9,9,9,9,9,9,9,9, + 9,9,9,9,9,9,9,9,9,9,9,9,9,9,9,9, 9,9,9,9,9,9,9,9,9,9,9,9,9,9,9,9, + 9,9,9,9,9,9,9,9,9,9,9,9,9,9,9,9, 9,9,9,9,9,9,9,9,9,9,9,9,9,9,9,9, + 7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7, 7,7,7,7,7,7,7,7,8,8,8,8,8,8,8,8 +}; +static const stbi_uc stbi__zdefault_distance[32] = +{ + 5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5 +}; +/* +Init algorithm: +{ + int i; // use <= to match clearly with spec + for (i=0; i <= 143; ++i) stbi__zdefault_length[i] = 8; + for ( ; i <= 255; ++i) stbi__zdefault_length[i] = 9; + for ( ; i <= 279; ++i) stbi__zdefault_length[i] = 7; + for ( ; i <= 287; ++i) stbi__zdefault_length[i] = 8; + + for (i=0; i <= 31; ++i) stbi__zdefault_distance[i] = 5; +} +*/ + +static int stbi__parse_zlib(stbi__zbuf *a, int parse_header) +{ + int final, type; + if (parse_header) + if (!stbi__parse_zlib_header(a)) return 0; + a->num_bits = 0; + a->code_buffer = 0; + do { + final = stbi__zreceive(a,1); + type = stbi__zreceive(a,2); + if (type == 0) { + if (!stbi__parse_uncompressed_block(a)) return 0; + } else if (type == 3) { + return 0; + } else { + if (type == 1) { + // use fixed code lengths + if (!stbi__zbuild_huffman(&a->z_length , stbi__zdefault_length , 288)) return 0; + if (!stbi__zbuild_huffman(&a->z_distance, stbi__zdefault_distance, 32)) return 0; + } else { + if (!stbi__compute_huffman_codes(a)) return 0; + } + if (!stbi__parse_huffman_block(a)) return 0; + } + } while (!final); + return 1; +} + +static int stbi__do_zlib(stbi__zbuf *a, char *obuf, int olen, int exp, int parse_header) +{ + a->zout_start = obuf; + a->zout = obuf; + a->zout_end = obuf + olen; + a->z_expandable = exp; + + return stbi__parse_zlib(a, parse_header); +} + +STBIDEF char *stbi_zlib_decode_malloc_guesssize(const char *buffer, int len, int initial_size, int *outlen) +{ + stbi__zbuf a; + char *p = (char *) stbi__malloc(initial_size); + if (p == NULL) return NULL; + a.zbuffer = (stbi_uc *) buffer; + a.zbuffer_end = (stbi_uc *) buffer + len; + if (stbi__do_zlib(&a, p, initial_size, 1, 1)) { + if (outlen) *outlen = (int) (a.zout - a.zout_start); + return a.zout_start; + } else { + STBI_FREE(a.zout_start); + return NULL; + } +} + +STBIDEF char *stbi_zlib_decode_malloc(char const *buffer, int len, int *outlen) +{ + return stbi_zlib_decode_malloc_guesssize(buffer, len, 16384, outlen); +} + +STBIDEF char *stbi_zlib_decode_malloc_guesssize_headerflag(const char *buffer, int len, int initial_size, int *outlen, int parse_header) +{ + stbi__zbuf a; + char *p = (char *) stbi__malloc(initial_size); + if (p == NULL) return NULL; + a.zbuffer = (stbi_uc *) buffer; + a.zbuffer_end = (stbi_uc *) buffer + len; + if (stbi__do_zlib(&a, p, initial_size, 1, parse_header)) { + if (outlen) *outlen = (int) (a.zout - a.zout_start); + return a.zout_start; + } else { + STBI_FREE(a.zout_start); + return NULL; + } +} + +STBIDEF int stbi_zlib_decode_buffer(char *obuffer, int olen, char const *ibuffer, int ilen) +{ + stbi__zbuf a; + a.zbuffer = (stbi_uc *) ibuffer; + a.zbuffer_end = (stbi_uc *) ibuffer + ilen; + if (stbi__do_zlib(&a, obuffer, olen, 0, 1)) + return (int) (a.zout - a.zout_start); + else + return -1; +} + +STBIDEF char *stbi_zlib_decode_noheader_malloc(char const *buffer, int len, int *outlen) +{ + stbi__zbuf a; + char *p = (char *) stbi__malloc(16384); + if (p == NULL) return NULL; + a.zbuffer = (stbi_uc *) buffer; + a.zbuffer_end = (stbi_uc *) buffer+len; + if (stbi__do_zlib(&a, p, 16384, 1, 0)) { + if (outlen) *outlen = (int) (a.zout - a.zout_start); + return a.zout_start; + } else { + STBI_FREE(a.zout_start); + return NULL; + } +} + +STBIDEF int stbi_zlib_decode_noheader_buffer(char *obuffer, int olen, const char *ibuffer, int ilen) +{ + stbi__zbuf a; + a.zbuffer = (stbi_uc *) ibuffer; + a.zbuffer_end = (stbi_uc *) ibuffer + ilen; + if (stbi__do_zlib(&a, obuffer, olen, 0, 0)) + return (int) (a.zout - a.zout_start); + else + return -1; +} +#endif + +// public domain "baseline" PNG decoder v0.10 Sean Barrett 2006-11-18 +// simple implementation +// - only 8-bit samples +// - no CRC checking +// - allocates lots of intermediate memory +// - avoids problem of streaming data between subsystems +// - avoids explicit window management +// performance +// - uses stb_zlib, a PD zlib implementation with fast huffman decoding + +#ifndef STBI_NO_PNG +typedef struct +{ + stbi__uint32 length; + stbi__uint32 type; +} stbi__pngchunk; + +static stbi__pngchunk stbi__get_chunk_header(stbi__context *s) +{ + stbi__pngchunk c; + c.length = stbi__get32be(s); + c.type = stbi__get32be(s); + return c; +} + +static int stbi__check_png_header(stbi__context *s) +{ + static const stbi_uc png_sig[8] = { 137,80,78,71,13,10,26,10 }; + int i; + for (i=0; i < 8; ++i) + if (stbi__get8(s) != png_sig[i]) return stbi__err("bad png sig","Not a PNG"); + return 1; +} + +typedef struct +{ + stbi__context *s; + stbi_uc *idata, *expanded, *out; + int depth; +} stbi__png; + + +enum { + STBI__F_none=0, + STBI__F_sub=1, + STBI__F_up=2, + STBI__F_avg=3, + STBI__F_paeth=4, + // synthetic filters used for first scanline to avoid needing a dummy row of 0s + STBI__F_avg_first, + STBI__F_paeth_first +}; + +static stbi_uc first_row_filter[5] = +{ + STBI__F_none, + STBI__F_sub, + STBI__F_none, + STBI__F_avg_first, + STBI__F_paeth_first +}; + +static int stbi__paeth(int a, int b, int c) +{ + int p = a + b - c; + int pa = abs(p-a); + int pb = abs(p-b); + int pc = abs(p-c); + if (pa <= pb && pa <= pc) return a; + if (pb <= pc) return b; + return c; +} + +static const stbi_uc stbi__depth_scale_table[9] = { 0, 0xff, 0x55, 0, 0x11, 0,0,0, 0x01 }; + +// create the png data from post-deflated data +static int stbi__create_png_image_raw(stbi__png *a, stbi_uc *raw, stbi__uint32 raw_len, int out_n, stbi__uint32 x, stbi__uint32 y, int depth, int color) +{ + int bytes = (depth == 16? 2 : 1); + stbi__context *s = a->s; + stbi__uint32 i,j,stride = x*out_n*bytes; + stbi__uint32 img_len, img_width_bytes; + int k; + int img_n = s->img_n; // copy it into a local for later + + int output_bytes = out_n*bytes; + int filter_bytes = img_n*bytes; + int width = x; + + STBI_ASSERT(out_n == s->img_n || out_n == s->img_n+1); + a->out = (stbi_uc *) stbi__malloc_mad3(x, y, output_bytes, 0); // extra bytes to write off the end into + if (!a->out) return stbi__err("outofmem", "Out of memory"); + + if (!stbi__mad3sizes_valid(img_n, x, depth, 7)) return stbi__err("too large", "Corrupt PNG"); + img_width_bytes = (((img_n * x * depth) + 7) >> 3); + img_len = (img_width_bytes + 1) * y; + + // we used to check for exact match between raw_len and img_len on non-interlaced PNGs, + // but issue #276 reported a PNG in the wild that had extra data at the end (all zeros), + // so just check for raw_len < img_len always. + if (raw_len < img_len) return stbi__err("not enough pixels","Corrupt PNG"); + + for (j=0; j < y; ++j) { + stbi_uc *cur = a->out + stride*j; + stbi_uc *prior; + int filter = *raw++; + + if (filter > 4) + return stbi__err("invalid filter","Corrupt PNG"); + + if (depth < 8) { + STBI_ASSERT(img_width_bytes <= x); + cur += x*out_n - img_width_bytes; // store output to the rightmost img_len bytes, so we can decode in place + filter_bytes = 1; + width = img_width_bytes; + } + prior = cur - stride; // bugfix: need to compute this after 'cur +=' computation above + + // if first row, use special filter that doesn't sample previous row + if (j == 0) filter = first_row_filter[filter]; + + // handle first byte explicitly + for (k=0; k < filter_bytes; ++k) { + switch (filter) { + case STBI__F_none : cur[k] = raw[k]; break; + case STBI__F_sub : cur[k] = raw[k]; break; + case STBI__F_up : cur[k] = STBI__BYTECAST(raw[k] + prior[k]); break; + case STBI__F_avg : cur[k] = STBI__BYTECAST(raw[k] + (prior[k]>>1)); break; + case STBI__F_paeth : cur[k] = STBI__BYTECAST(raw[k] + stbi__paeth(0,prior[k],0)); break; + case STBI__F_avg_first : cur[k] = raw[k]; break; + case STBI__F_paeth_first: cur[k] = raw[k]; break; + } + } + + if (depth == 8) { + if (img_n != out_n) + cur[img_n] = 255; // first pixel + raw += img_n; + cur += out_n; + prior += out_n; + } else if (depth == 16) { + if (img_n != out_n) { + cur[filter_bytes] = 255; // first pixel top byte + cur[filter_bytes+1] = 255; // first pixel bottom byte + } + raw += filter_bytes; + cur += output_bytes; + prior += output_bytes; + } else { + raw += 1; + cur += 1; + prior += 1; + } + + // this is a little gross, so that we don't switch per-pixel or per-component + if (depth < 8 || img_n == out_n) { + int nk = (width - 1)*filter_bytes; + #define STBI__CASE(f) \ + case f: \ + for (k=0; k < nk; ++k) + switch (filter) { + // "none" filter turns into a memcpy here; make that explicit. + case STBI__F_none: memcpy(cur, raw, nk); break; + STBI__CASE(STBI__F_sub) { cur[k] = STBI__BYTECAST(raw[k] + cur[k-filter_bytes]); } break; + STBI__CASE(STBI__F_up) { cur[k] = STBI__BYTECAST(raw[k] + prior[k]); } break; + STBI__CASE(STBI__F_avg) { cur[k] = STBI__BYTECAST(raw[k] + ((prior[k] + cur[k-filter_bytes])>>1)); } break; + STBI__CASE(STBI__F_paeth) { cur[k] = STBI__BYTECAST(raw[k] + stbi__paeth(cur[k-filter_bytes],prior[k],prior[k-filter_bytes])); } break; + STBI__CASE(STBI__F_avg_first) { cur[k] = STBI__BYTECAST(raw[k] + (cur[k-filter_bytes] >> 1)); } break; + STBI__CASE(STBI__F_paeth_first) { cur[k] = STBI__BYTECAST(raw[k] + stbi__paeth(cur[k-filter_bytes],0,0)); } break; + } + #undef STBI__CASE + raw += nk; + } else { + STBI_ASSERT(img_n+1 == out_n); + #define STBI__CASE(f) \ + case f: \ + for (i=x-1; i >= 1; --i, cur[filter_bytes]=255,raw+=filter_bytes,cur+=output_bytes,prior+=output_bytes) \ + for (k=0; k < filter_bytes; ++k) + switch (filter) { + STBI__CASE(STBI__F_none) { cur[k] = raw[k]; } break; + STBI__CASE(STBI__F_sub) { cur[k] = STBI__BYTECAST(raw[k] + cur[k- output_bytes]); } break; + STBI__CASE(STBI__F_up) { cur[k] = STBI__BYTECAST(raw[k] + prior[k]); } break; + STBI__CASE(STBI__F_avg) { cur[k] = STBI__BYTECAST(raw[k] + ((prior[k] + cur[k- output_bytes])>>1)); } break; + STBI__CASE(STBI__F_paeth) { cur[k] = STBI__BYTECAST(raw[k] + stbi__paeth(cur[k- output_bytes],prior[k],prior[k- output_bytes])); } break; + STBI__CASE(STBI__F_avg_first) { cur[k] = STBI__BYTECAST(raw[k] + (cur[k- output_bytes] >> 1)); } break; + STBI__CASE(STBI__F_paeth_first) { cur[k] = STBI__BYTECAST(raw[k] + stbi__paeth(cur[k- output_bytes],0,0)); } break; + } + #undef STBI__CASE + + // the loop above sets the high byte of the pixels' alpha, but for + // 16 bit png files we also need the low byte set. we'll do that here. + if (depth == 16) { + cur = a->out + stride*j; // start at the beginning of the row again + for (i=0; i < x; ++i,cur+=output_bytes) { + cur[filter_bytes+1] = 255; + } + } + } + } + + // we make a separate pass to expand bits to pixels; for performance, + // this could run two scanlines behind the above code, so it won't + // intefere with filtering but will still be in the cache. + if (depth < 8) { + for (j=0; j < y; ++j) { + stbi_uc *cur = a->out + stride*j; + stbi_uc *in = a->out + stride*j + x*out_n - img_width_bytes; + // unpack 1/2/4-bit into a 8-bit buffer. allows us to keep the common 8-bit path optimal at minimal cost for 1/2/4-bit + // png guarante byte alignment, if width is not multiple of 8/4/2 we'll decode dummy trailing data that will be skipped in the later loop + stbi_uc scale = (color == 0) ? stbi__depth_scale_table[depth] : 1; // scale grayscale values to 0..255 range + + // note that the final byte might overshoot and write more data than desired. + // we can allocate enough data that this never writes out of memory, but it + // could also overwrite the next scanline. can it overwrite non-empty data + // on the next scanline? yes, consider 1-pixel-wide scanlines with 1-bit-per-pixel. + // so we need to explicitly clamp the final ones + + if (depth == 4) { + for (k=x*img_n; k >= 2; k-=2, ++in) { + *cur++ = scale * ((*in >> 4) ); + *cur++ = scale * ((*in ) & 0x0f); + } + if (k > 0) *cur++ = scale * ((*in >> 4) ); + } else if (depth == 2) { + for (k=x*img_n; k >= 4; k-=4, ++in) { + *cur++ = scale * ((*in >> 6) ); + *cur++ = scale * ((*in >> 4) & 0x03); + *cur++ = scale * ((*in >> 2) & 0x03); + *cur++ = scale * ((*in ) & 0x03); + } + if (k > 0) *cur++ = scale * ((*in >> 6) ); + if (k > 1) *cur++ = scale * ((*in >> 4) & 0x03); + if (k > 2) *cur++ = scale * ((*in >> 2) & 0x03); + } else if (depth == 1) { + for (k=x*img_n; k >= 8; k-=8, ++in) { + *cur++ = scale * ((*in >> 7) ); + *cur++ = scale * ((*in >> 6) & 0x01); + *cur++ = scale * ((*in >> 5) & 0x01); + *cur++ = scale * ((*in >> 4) & 0x01); + *cur++ = scale * ((*in >> 3) & 0x01); + *cur++ = scale * ((*in >> 2) & 0x01); + *cur++ = scale * ((*in >> 1) & 0x01); + *cur++ = scale * ((*in ) & 0x01); + } + if (k > 0) *cur++ = scale * ((*in >> 7) ); + if (k > 1) *cur++ = scale * ((*in >> 6) & 0x01); + if (k > 2) *cur++ = scale * ((*in >> 5) & 0x01); + if (k > 3) *cur++ = scale * ((*in >> 4) & 0x01); + if (k > 4) *cur++ = scale * ((*in >> 3) & 0x01); + if (k > 5) *cur++ = scale * ((*in >> 2) & 0x01); + if (k > 6) *cur++ = scale * ((*in >> 1) & 0x01); + } + if (img_n != out_n) { + int q; + // insert alpha = 255 + cur = a->out + stride*j; + if (img_n == 1) { + for (q=x-1; q >= 0; --q) { + cur[q*2+1] = 255; + cur[q*2+0] = cur[q]; + } + } else { + STBI_ASSERT(img_n == 3); + for (q=x-1; q >= 0; --q) { + cur[q*4+3] = 255; + cur[q*4+2] = cur[q*3+2]; + cur[q*4+1] = cur[q*3+1]; + cur[q*4+0] = cur[q*3+0]; + } + } + } + } + } else if (depth == 16) { + // force the image data from big-endian to platform-native. + // this is done in a separate pass due to the decoding relying + // on the data being untouched, but could probably be done + // per-line during decode if care is taken. + stbi_uc *cur = a->out; + stbi__uint16 *cur16 = (stbi__uint16*)cur; + + for(i=0; i < x*y*out_n; ++i,cur16++,cur+=2) { + *cur16 = (cur[0] << 8) | cur[1]; + } + } + + return 1; +} + +static int stbi__create_png_image(stbi__png *a, stbi_uc *image_data, stbi__uint32 image_data_len, int out_n, int depth, int color, int interlaced) +{ + int bytes = (depth == 16 ? 2 : 1); + int out_bytes = out_n * bytes; + stbi_uc *final; + int p; + if (!interlaced) + return stbi__create_png_image_raw(a, image_data, image_data_len, out_n, a->s->img_x, a->s->img_y, depth, color); + + // de-interlacing + final = (stbi_uc *) stbi__malloc_mad3(a->s->img_x, a->s->img_y, out_bytes, 0); + for (p=0; p < 7; ++p) { + int xorig[] = { 0,4,0,2,0,1,0 }; + int yorig[] = { 0,0,4,0,2,0,1 }; + int xspc[] = { 8,8,4,4,2,2,1 }; + int yspc[] = { 8,8,8,4,4,2,2 }; + int i,j,x,y; + // pass1_x[4] = 0, pass1_x[5] = 1, pass1_x[12] = 1 + x = (a->s->img_x - xorig[p] + xspc[p]-1) / xspc[p]; + y = (a->s->img_y - yorig[p] + yspc[p]-1) / yspc[p]; + if (x && y) { + stbi__uint32 img_len = ((((a->s->img_n * x * depth) + 7) >> 3) + 1) * y; + if (!stbi__create_png_image_raw(a, image_data, image_data_len, out_n, x, y, depth, color)) { + STBI_FREE(final); + return 0; + } + for (j=0; j < y; ++j) { + for (i=0; i < x; ++i) { + int out_y = j*yspc[p]+yorig[p]; + int out_x = i*xspc[p]+xorig[p]; + memcpy(final + out_y*a->s->img_x*out_bytes + out_x*out_bytes, + a->out + (j*x+i)*out_bytes, out_bytes); + } + } + STBI_FREE(a->out); + image_data += img_len; + image_data_len -= img_len; + } + } + a->out = final; + + return 1; +} + +static int stbi__compute_transparency(stbi__png *z, stbi_uc tc[3], int out_n) +{ + stbi__context *s = z->s; + stbi__uint32 i, pixel_count = s->img_x * s->img_y; + stbi_uc *p = z->out; + + // compute color-based transparency, assuming we've + // already got 255 as the alpha value in the output + STBI_ASSERT(out_n == 2 || out_n == 4); + + if (out_n == 2) { + for (i=0; i < pixel_count; ++i) { + p[1] = (p[0] == tc[0] ? 0 : 255); + p += 2; + } + } else { + for (i=0; i < pixel_count; ++i) { + if (p[0] == tc[0] && p[1] == tc[1] && p[2] == tc[2]) + p[3] = 0; + p += 4; + } + } + return 1; +} + +static int stbi__compute_transparency16(stbi__png *z, stbi__uint16 tc[3], int out_n) +{ + stbi__context *s = z->s; + stbi__uint32 i, pixel_count = s->img_x * s->img_y; + stbi__uint16 *p = (stbi__uint16*) z->out; + + // compute color-based transparency, assuming we've + // already got 65535 as the alpha value in the output + STBI_ASSERT(out_n == 2 || out_n == 4); + + if (out_n == 2) { + for (i = 0; i < pixel_count; ++i) { + p[1] = (p[0] == tc[0] ? 0 : 65535); + p += 2; + } + } else { + for (i = 0; i < pixel_count; ++i) { + if (p[0] == tc[0] && p[1] == tc[1] && p[2] == tc[2]) + p[3] = 0; + p += 4; + } + } + return 1; +} + +static int stbi__expand_png_palette(stbi__png *a, stbi_uc *palette, int len, int pal_img_n) +{ + stbi__uint32 i, pixel_count = a->s->img_x * a->s->img_y; + stbi_uc *p, *temp_out, *orig = a->out; + + p = (stbi_uc *) stbi__malloc_mad2(pixel_count, pal_img_n, 0); + if (p == NULL) return stbi__err("outofmem", "Out of memory"); + + // between here and free(out) below, exitting would leak + temp_out = p; + + if (pal_img_n == 3) { + for (i=0; i < pixel_count; ++i) { + int n = orig[i]*4; + p[0] = palette[n ]; + p[1] = palette[n+1]; + p[2] = palette[n+2]; + p += 3; + } + } else { + for (i=0; i < pixel_count; ++i) { + int n = orig[i]*4; + p[0] = palette[n ]; + p[1] = palette[n+1]; + p[2] = palette[n+2]; + p[3] = palette[n+3]; + p += 4; + } + } + STBI_FREE(a->out); + a->out = temp_out; + + STBI_NOTUSED(len); + + return 1; +} + +static int stbi__unpremultiply_on_load = 0; +static int stbi__de_iphone_flag = 0; + +STBIDEF void stbi_set_unpremultiply_on_load(int flag_true_if_should_unpremultiply) +{ + stbi__unpremultiply_on_load = flag_true_if_should_unpremultiply; +} + +STBIDEF void stbi_convert_iphone_png_to_rgb(int flag_true_if_should_convert) +{ + stbi__de_iphone_flag = flag_true_if_should_convert; +} + +static void stbi__de_iphone(stbi__png *z) +{ + stbi__context *s = z->s; + stbi__uint32 i, pixel_count = s->img_x * s->img_y; + stbi_uc *p = z->out; + + if (s->img_out_n == 3) { // convert bgr to rgb + for (i=0; i < pixel_count; ++i) { + stbi_uc t = p[0]; + p[0] = p[2]; + p[2] = t; + p += 3; + } + } else { + STBI_ASSERT(s->img_out_n == 4); + if (stbi__unpremultiply_on_load) { + // convert bgr to rgb and unpremultiply + for (i=0; i < pixel_count; ++i) { + stbi_uc a = p[3]; + stbi_uc t = p[0]; + if (a) { + stbi_uc half = a / 2; + p[0] = (p[2] * 255 + half) / a; + p[1] = (p[1] * 255 + half) / a; + p[2] = ( t * 255 + half) / a; + } else { + p[0] = p[2]; + p[2] = t; + } + p += 4; + } + } else { + // convert bgr to rgb + for (i=0; i < pixel_count; ++i) { + stbi_uc t = p[0]; + p[0] = p[2]; + p[2] = t; + p += 4; + } + } + } +} + +#define STBI__PNG_TYPE(a,b,c,d) (((unsigned) (a) << 24) + ((unsigned) (b) << 16) + ((unsigned) (c) << 8) + (unsigned) (d)) + +static int stbi__parse_png_file(stbi__png *z, int scan, int req_comp) +{ + stbi_uc palette[1024], pal_img_n=0; + stbi_uc has_trans=0, tc[3]={0}; + stbi__uint16 tc16[3]; + stbi__uint32 ioff=0, idata_limit=0, i, pal_len=0; + int first=1,k,interlace=0, color=0, is_iphone=0; + stbi__context *s = z->s; + + z->expanded = NULL; + z->idata = NULL; + z->out = NULL; + + if (!stbi__check_png_header(s)) return 0; + + if (scan == STBI__SCAN_type) return 1; + + for (;;) { + stbi__pngchunk c = stbi__get_chunk_header(s); + switch (c.type) { + case STBI__PNG_TYPE('C','g','B','I'): + is_iphone = 1; + stbi__skip(s, c.length); + break; + case STBI__PNG_TYPE('I','H','D','R'): { + int comp,filter; + if (!first) return stbi__err("multiple IHDR","Corrupt PNG"); + first = 0; + if (c.length != 13) return stbi__err("bad IHDR len","Corrupt PNG"); + s->img_x = stbi__get32be(s); if (s->img_x > (1 << 24)) return stbi__err("too large","Very large image (corrupt?)"); + s->img_y = stbi__get32be(s); if (s->img_y > (1 << 24)) return stbi__err("too large","Very large image (corrupt?)"); + z->depth = stbi__get8(s); if (z->depth != 1 && z->depth != 2 && z->depth != 4 && z->depth != 8 && z->depth != 16) return stbi__err("1/2/4/8/16-bit only","PNG not supported: 1/2/4/8/16-bit only"); + color = stbi__get8(s); if (color > 6) return stbi__err("bad ctype","Corrupt PNG"); + if (color == 3 && z->depth == 16) return stbi__err("bad ctype","Corrupt PNG"); + if (color == 3) pal_img_n = 3; else if (color & 1) return stbi__err("bad ctype","Corrupt PNG"); + comp = stbi__get8(s); if (comp) return stbi__err("bad comp method","Corrupt PNG"); + filter= stbi__get8(s); if (filter) return stbi__err("bad filter method","Corrupt PNG"); + interlace = stbi__get8(s); if (interlace>1) return stbi__err("bad interlace method","Corrupt PNG"); + if (!s->img_x || !s->img_y) return stbi__err("0-pixel image","Corrupt PNG"); + if (!pal_img_n) { + s->img_n = (color & 2 ? 3 : 1) + (color & 4 ? 1 : 0); + if ((1 << 30) / s->img_x / s->img_n < s->img_y) return stbi__err("too large", "Image too large to decode"); + if (scan == STBI__SCAN_header) return 1; + } else { + // if paletted, then pal_n is our final components, and + // img_n is # components to decompress/filter. + s->img_n = 1; + if ((1 << 30) / s->img_x / 4 < s->img_y) return stbi__err("too large","Corrupt PNG"); + // if SCAN_header, have to scan to see if we have a tRNS + } + break; + } + + case STBI__PNG_TYPE('P','L','T','E'): { + if (first) return stbi__err("first not IHDR", "Corrupt PNG"); + if (c.length > 256*3) return stbi__err("invalid PLTE","Corrupt PNG"); + pal_len = c.length / 3; + if (pal_len * 3 != c.length) return stbi__err("invalid PLTE","Corrupt PNG"); + for (i=0; i < pal_len; ++i) { + palette[i*4+0] = stbi__get8(s); + palette[i*4+1] = stbi__get8(s); + palette[i*4+2] = stbi__get8(s); + palette[i*4+3] = 255; + } + break; + } + + case STBI__PNG_TYPE('t','R','N','S'): { + if (first) return stbi__err("first not IHDR", "Corrupt PNG"); + if (z->idata) return stbi__err("tRNS after IDAT","Corrupt PNG"); + if (pal_img_n) { + if (scan == STBI__SCAN_header) { s->img_n = 4; return 1; } + if (pal_len == 0) return stbi__err("tRNS before PLTE","Corrupt PNG"); + if (c.length > pal_len) return stbi__err("bad tRNS len","Corrupt PNG"); + pal_img_n = 4; + for (i=0; i < c.length; ++i) + palette[i*4+3] = stbi__get8(s); + } else { + if (!(s->img_n & 1)) return stbi__err("tRNS with alpha","Corrupt PNG"); + if (c.length != (stbi__uint32) s->img_n*2) return stbi__err("bad tRNS len","Corrupt PNG"); + has_trans = 1; + if (z->depth == 16) { + for (k = 0; k < s->img_n; ++k) tc16[k] = (stbi__uint16)stbi__get16be(s); // copy the values as-is + } else { + for (k = 0; k < s->img_n; ++k) tc[k] = (stbi_uc)(stbi__get16be(s) & 255) * stbi__depth_scale_table[z->depth]; // non 8-bit images will be larger + } + } + break; + } + + case STBI__PNG_TYPE('I','D','A','T'): { + if (first) return stbi__err("first not IHDR", "Corrupt PNG"); + if (pal_img_n && !pal_len) return stbi__err("no PLTE","Corrupt PNG"); + if (scan == STBI__SCAN_header) { s->img_n = pal_img_n; return 1; } + if ((int)(ioff + c.length) < (int)ioff) return 0; + if (ioff + c.length > idata_limit) { + stbi__uint32 idata_limit_old = idata_limit; + stbi_uc *p; + if (idata_limit == 0) idata_limit = c.length > 4096 ? c.length : 4096; + while (ioff + c.length > idata_limit) + idata_limit *= 2; + STBI_NOTUSED(idata_limit_old); + p = (stbi_uc *) STBI_REALLOC_SIZED(z->idata, idata_limit_old, idata_limit); if (p == NULL) return stbi__err("outofmem", "Out of memory"); + z->idata = p; + } + if (!stbi__getn(s, z->idata+ioff,c.length)) return stbi__err("outofdata","Corrupt PNG"); + ioff += c.length; + break; + } + + case STBI__PNG_TYPE('I','E','N','D'): { + stbi__uint32 raw_len, bpl; + if (first) return stbi__err("first not IHDR", "Corrupt PNG"); + if (scan != STBI__SCAN_load) return 1; + if (z->idata == NULL) return stbi__err("no IDAT","Corrupt PNG"); + // initial guess for decoded data size to avoid unnecessary reallocs + bpl = (s->img_x * z->depth + 7) / 8; // bytes per line, per component + raw_len = bpl * s->img_y * s->img_n /* pixels */ + s->img_y /* filter mode per row */; + z->expanded = (stbi_uc *) stbi_zlib_decode_malloc_guesssize_headerflag((char *) z->idata, ioff, raw_len, (int *) &raw_len, !is_iphone); + if (z->expanded == NULL) return 0; // zlib should set error + STBI_FREE(z->idata); z->idata = NULL; + if ((req_comp == s->img_n+1 && req_comp != 3 && !pal_img_n) || has_trans) + s->img_out_n = s->img_n+1; + else + s->img_out_n = s->img_n; + if (!stbi__create_png_image(z, z->expanded, raw_len, s->img_out_n, z->depth, color, interlace)) return 0; + if (has_trans) { + if (z->depth == 16) { + if (!stbi__compute_transparency16(z, tc16, s->img_out_n)) return 0; + } else { + if (!stbi__compute_transparency(z, tc, s->img_out_n)) return 0; + } + } + if (is_iphone && stbi__de_iphone_flag && s->img_out_n > 2) + stbi__de_iphone(z); + if (pal_img_n) { + // pal_img_n == 3 or 4 + s->img_n = pal_img_n; // record the actual colors we had + s->img_out_n = pal_img_n; + if (req_comp >= 3) s->img_out_n = req_comp; + if (!stbi__expand_png_palette(z, palette, pal_len, s->img_out_n)) + return 0; + } else if (has_trans) { + // non-paletted image with tRNS -> source image has (constant) alpha + ++s->img_n; + } + STBI_FREE(z->expanded); z->expanded = NULL; + // end of PNG chunk, read and skip CRC + stbi__get32be(s); + return 1; + } + + default: + // if critical, fail + if (first) return stbi__err("first not IHDR", "Corrupt PNG"); + if ((c.type & (1 << 29)) == 0) { + #ifndef STBI_NO_FAILURE_STRINGS + // not threadsafe + static char invalid_chunk[] = "XXXX PNG chunk not known"; + invalid_chunk[0] = STBI__BYTECAST(c.type >> 24); + invalid_chunk[1] = STBI__BYTECAST(c.type >> 16); + invalid_chunk[2] = STBI__BYTECAST(c.type >> 8); + invalid_chunk[3] = STBI__BYTECAST(c.type >> 0); + #endif + return stbi__err(invalid_chunk, "PNG not supported: unknown PNG chunk type"); + } + stbi__skip(s, c.length); + break; + } + // end of PNG chunk, read and skip CRC + stbi__get32be(s); + } +} + +static void *stbi__do_png(stbi__png *p, int *x, int *y, int *n, int req_comp, stbi__result_info *ri) +{ + void *result=NULL; + if (req_comp < 0 || req_comp > 4) return stbi__errpuc("bad req_comp", "Internal error"); + if (stbi__parse_png_file(p, STBI__SCAN_load, req_comp)) { + if (p->depth < 8) + ri->bits_per_channel = 8; + else + ri->bits_per_channel = p->depth; + result = p->out; + p->out = NULL; + if (req_comp && req_comp != p->s->img_out_n) { + if (ri->bits_per_channel == 8) + result = stbi__convert_format((unsigned char *) result, p->s->img_out_n, req_comp, p->s->img_x, p->s->img_y); + else + result = stbi__convert_format16((stbi__uint16 *) result, p->s->img_out_n, req_comp, p->s->img_x, p->s->img_y); + p->s->img_out_n = req_comp; + if (result == NULL) return result; + } + *x = p->s->img_x; + *y = p->s->img_y; + if (n) *n = p->s->img_n; + } + STBI_FREE(p->out); p->out = NULL; + STBI_FREE(p->expanded); p->expanded = NULL; + STBI_FREE(p->idata); p->idata = NULL; + + return result; +} + +static void *stbi__png_load(stbi__context *s, int *x, int *y, int *comp, int req_comp, stbi__result_info *ri) +{ + stbi__png p; + p.s = s; + return stbi__do_png(&p, x,y,comp,req_comp, ri); +} + +static int stbi__png_test(stbi__context *s) +{ + int r; + r = stbi__check_png_header(s); + stbi__rewind(s); + return r; +} + +static int stbi__png_info_raw(stbi__png *p, int *x, int *y, int *comp) +{ + if (!stbi__parse_png_file(p, STBI__SCAN_header, 0)) { + stbi__rewind( p->s ); + return 0; + } + if (x) *x = p->s->img_x; + if (y) *y = p->s->img_y; + if (comp) *comp = p->s->img_n; + return 1; +} + +static int stbi__png_info(stbi__context *s, int *x, int *y, int *comp) +{ + stbi__png p; + p.s = s; + return stbi__png_info_raw(&p, x, y, comp); +} + +static int stbi__png_is16(stbi__context *s) +{ + stbi__png p; + p.s = s; + if (!stbi__png_info_raw(&p, NULL, NULL, NULL)) + return 0; + if (p.depth != 16) { + stbi__rewind(p.s); + return 0; + } + return 1; +} +#endif + +// Microsoft/Windows BMP image + +#ifndef STBI_NO_BMP +static int stbi__bmp_test_raw(stbi__context *s) +{ + int r; + int sz; + if (stbi__get8(s) != 'B') return 0; + if (stbi__get8(s) != 'M') return 0; + stbi__get32le(s); // discard filesize + stbi__get16le(s); // discard reserved + stbi__get16le(s); // discard reserved + stbi__get32le(s); // discard data offset + sz = stbi__get32le(s); + r = (sz == 12 || sz == 40 || sz == 56 || sz == 108 || sz == 124); + return r; +} + +static int stbi__bmp_test(stbi__context *s) +{ + int r = stbi__bmp_test_raw(s); + stbi__rewind(s); + return r; +} + + +// returns 0..31 for the highest set bit +static int stbi__high_bit(unsigned int z) +{ + int n=0; + if (z == 0) return -1; + if (z >= 0x10000) { n += 16; z >>= 16; } + if (z >= 0x00100) { n += 8; z >>= 8; } + if (z >= 0x00010) { n += 4; z >>= 4; } + if (z >= 0x00004) { n += 2; z >>= 2; } + if (z >= 0x00002) { n += 1;/* >>= 1;*/ } + return n; +} + +static int stbi__bitcount(unsigned int a) +{ + a = (a & 0x55555555) + ((a >> 1) & 0x55555555); // max 2 + a = (a & 0x33333333) + ((a >> 2) & 0x33333333); // max 4 + a = (a + (a >> 4)) & 0x0f0f0f0f; // max 8 per 4, now 8 bits + a = (a + (a >> 8)); // max 16 per 8 bits + a = (a + (a >> 16)); // max 32 per 8 bits + return a & 0xff; +} + +// extract an arbitrarily-aligned N-bit value (N=bits) +// from v, and then make it 8-bits long and fractionally +// extend it to full full range. +static int stbi__shiftsigned(unsigned int v, int shift, int bits) +{ + static unsigned int mul_table[9] = { + 0, + 0xff/*0b11111111*/, 0x55/*0b01010101*/, 0x49/*0b01001001*/, 0x11/*0b00010001*/, + 0x21/*0b00100001*/, 0x41/*0b01000001*/, 0x81/*0b10000001*/, 0x01/*0b00000001*/, + }; + static unsigned int shift_table[9] = { + 0, 0,0,1,0,2,4,6,0, + }; + if (shift < 0) + v <<= -shift; + else + v >>= shift; + STBI_ASSERT(v < 256); + v >>= (8-bits); + STBI_ASSERT(bits >= 0 && bits <= 8); + return (int) ((unsigned) v * mul_table[bits]) >> shift_table[bits]; +} + +typedef struct +{ + int bpp, offset, hsz; + unsigned int mr,mg,mb,ma, all_a; + int extra_read; +} stbi__bmp_data; + +static void *stbi__bmp_parse_header(stbi__context *s, stbi__bmp_data *info) +{ + int hsz; + if (stbi__get8(s) != 'B' || stbi__get8(s) != 'M') return stbi__errpuc("not BMP", "Corrupt BMP"); + stbi__get32le(s); // discard filesize + stbi__get16le(s); // discard reserved + stbi__get16le(s); // discard reserved + info->offset = stbi__get32le(s); + info->hsz = hsz = stbi__get32le(s); + info->mr = info->mg = info->mb = info->ma = 0; + info->extra_read = 14; + + if (hsz != 12 && hsz != 40 && hsz != 56 && hsz != 108 && hsz != 124) return stbi__errpuc("unknown BMP", "BMP type not supported: unknown"); + if (hsz == 12) { + s->img_x = stbi__get16le(s); + s->img_y = stbi__get16le(s); + } else { + s->img_x = stbi__get32le(s); + s->img_y = stbi__get32le(s); + } + if (stbi__get16le(s) != 1) return stbi__errpuc("bad BMP", "bad BMP"); + info->bpp = stbi__get16le(s); + if (hsz != 12) { + int compress = stbi__get32le(s); + if (compress == 1 || compress == 2) return stbi__errpuc("BMP RLE", "BMP type not supported: RLE"); + stbi__get32le(s); // discard sizeof + stbi__get32le(s); // discard hres + stbi__get32le(s); // discard vres + stbi__get32le(s); // discard colorsused + stbi__get32le(s); // discard max important + if (hsz == 40 || hsz == 56) { + if (hsz == 56) { + stbi__get32le(s); + stbi__get32le(s); + stbi__get32le(s); + stbi__get32le(s); + } + if (info->bpp == 16 || info->bpp == 32) { + if (compress == 0) { + if (info->bpp == 32) { + info->mr = 0xffu << 16; + info->mg = 0xffu << 8; + info->mb = 0xffu << 0; + info->ma = 0xffu << 24; + info->all_a = 0; // if all_a is 0 at end, then we loaded alpha channel but it was all 0 + } else { + info->mr = 31u << 10; + info->mg = 31u << 5; + info->mb = 31u << 0; + } + } else if (compress == 3) { + info->mr = stbi__get32le(s); + info->mg = stbi__get32le(s); + info->mb = stbi__get32le(s); + info->extra_read += 12; + // not documented, but generated by photoshop and handled by mspaint + if (info->mr == info->mg && info->mg == info->mb) { + // ?!?!? + return stbi__errpuc("bad BMP", "bad BMP"); + } + } else + return stbi__errpuc("bad BMP", "bad BMP"); + } + } else { + int i; + if (hsz != 108 && hsz != 124) + return stbi__errpuc("bad BMP", "bad BMP"); + info->mr = stbi__get32le(s); + info->mg = stbi__get32le(s); + info->mb = stbi__get32le(s); + info->ma = stbi__get32le(s); + stbi__get32le(s); // discard color space + for (i=0; i < 12; ++i) + stbi__get32le(s); // discard color space parameters + if (hsz == 124) { + stbi__get32le(s); // discard rendering intent + stbi__get32le(s); // discard offset of profile data + stbi__get32le(s); // discard size of profile data + stbi__get32le(s); // discard reserved + } + } + } + return (void *) 1; +} + + +static void *stbi__bmp_load(stbi__context *s, int *x, int *y, int *comp, int req_comp, stbi__result_info *ri) +{ + stbi_uc *out; + unsigned int mr=0,mg=0,mb=0,ma=0, all_a; + stbi_uc pal[256][4]; + int psize=0,i,j,width; + int flip_vertically, pad, target; + stbi__bmp_data info; + STBI_NOTUSED(ri); + + info.all_a = 255; + if (stbi__bmp_parse_header(s, &info) == NULL) + return NULL; // error code already set + + flip_vertically = ((int) s->img_y) > 0; + s->img_y = abs((int) s->img_y); + + mr = info.mr; + mg = info.mg; + mb = info.mb; + ma = info.ma; + all_a = info.all_a; + + if (info.hsz == 12) { + if (info.bpp < 24) + psize = (info.offset - info.extra_read - 24) / 3; + } else { + if (info.bpp < 16) + psize = (info.offset - info.extra_read - info.hsz) >> 2; + } + if (psize == 0) { + STBI_ASSERT(info.offset == (s->img_buffer - s->buffer_start)); + } + + if (info.bpp == 24 && ma == 0xff000000) + s->img_n = 3; + else + s->img_n = ma ? 4 : 3; + if (req_comp && req_comp >= 3) // we can directly decode 3 or 4 + target = req_comp; + else + target = s->img_n; // if they want monochrome, we'll post-convert + + // sanity-check size + if (!stbi__mad3sizes_valid(target, s->img_x, s->img_y, 0)) + return stbi__errpuc("too large", "Corrupt BMP"); + + out = (stbi_uc *) stbi__malloc_mad3(target, s->img_x, s->img_y, 0); + if (!out) return stbi__errpuc("outofmem", "Out of memory"); + if (info.bpp < 16) { + int z=0; + if (psize == 0 || psize > 256) { STBI_FREE(out); return stbi__errpuc("invalid", "Corrupt BMP"); } + for (i=0; i < psize; ++i) { + pal[i][2] = stbi__get8(s); + pal[i][1] = stbi__get8(s); + pal[i][0] = stbi__get8(s); + if (info.hsz != 12) stbi__get8(s); + pal[i][3] = 255; + } + stbi__skip(s, info.offset - info.extra_read - info.hsz - psize * (info.hsz == 12 ? 3 : 4)); + if (info.bpp == 1) width = (s->img_x + 7) >> 3; + else if (info.bpp == 4) width = (s->img_x + 1) >> 1; + else if (info.bpp == 8) width = s->img_x; + else { STBI_FREE(out); return stbi__errpuc("bad bpp", "Corrupt BMP"); } + pad = (-width)&3; + if (info.bpp == 1) { + for (j=0; j < (int) s->img_y; ++j) { + int bit_offset = 7, v = stbi__get8(s); + for (i=0; i < (int) s->img_x; ++i) { + int color = (v>>bit_offset)&0x1; + out[z++] = pal[color][0]; + out[z++] = pal[color][1]; + out[z++] = pal[color][2]; + if (target == 4) out[z++] = 255; + if (i+1 == (int) s->img_x) break; + if((--bit_offset) < 0) { + bit_offset = 7; + v = stbi__get8(s); + } + } + stbi__skip(s, pad); + } + } else { + for (j=0; j < (int) s->img_y; ++j) { + for (i=0; i < (int) s->img_x; i += 2) { + int v=stbi__get8(s),v2=0; + if (info.bpp == 4) { + v2 = v & 15; + v >>= 4; + } + out[z++] = pal[v][0]; + out[z++] = pal[v][1]; + out[z++] = pal[v][2]; + if (target == 4) out[z++] = 255; + if (i+1 == (int) s->img_x) break; + v = (info.bpp == 8) ? stbi__get8(s) : v2; + out[z++] = pal[v][0]; + out[z++] = pal[v][1]; + out[z++] = pal[v][2]; + if (target == 4) out[z++] = 255; + } + stbi__skip(s, pad); + } + } + } else { + int rshift=0,gshift=0,bshift=0,ashift=0,rcount=0,gcount=0,bcount=0,acount=0; + int z = 0; + int easy=0; + stbi__skip(s, info.offset - info.extra_read - info.hsz); + if (info.bpp == 24) width = 3 * s->img_x; + else if (info.bpp == 16) width = 2*s->img_x; + else /* bpp = 32 and pad = 0 */ width=0; + pad = (-width) & 3; + if (info.bpp == 24) { + easy = 1; + } else if (info.bpp == 32) { + if (mb == 0xff && mg == 0xff00 && mr == 0x00ff0000 && ma == 0xff000000) + easy = 2; + } + if (!easy) { + if (!mr || !mg || !mb) { STBI_FREE(out); return stbi__errpuc("bad masks", "Corrupt BMP"); } + // right shift amt to put high bit in position #7 + rshift = stbi__high_bit(mr)-7; rcount = stbi__bitcount(mr); + gshift = stbi__high_bit(mg)-7; gcount = stbi__bitcount(mg); + bshift = stbi__high_bit(mb)-7; bcount = stbi__bitcount(mb); + ashift = stbi__high_bit(ma)-7; acount = stbi__bitcount(ma); + } + for (j=0; j < (int) s->img_y; ++j) { + if (easy) { + for (i=0; i < (int) s->img_x; ++i) { + unsigned char a; + out[z+2] = stbi__get8(s); + out[z+1] = stbi__get8(s); + out[z+0] = stbi__get8(s); + z += 3; + a = (easy == 2 ? stbi__get8(s) : 255); + all_a |= a; + if (target == 4) out[z++] = a; + } + } else { + int bpp = info.bpp; + for (i=0; i < (int) s->img_x; ++i) { + stbi__uint32 v = (bpp == 16 ? (stbi__uint32) stbi__get16le(s) : stbi__get32le(s)); + unsigned int a; + out[z++] = STBI__BYTECAST(stbi__shiftsigned(v & mr, rshift, rcount)); + out[z++] = STBI__BYTECAST(stbi__shiftsigned(v & mg, gshift, gcount)); + out[z++] = STBI__BYTECAST(stbi__shiftsigned(v & mb, bshift, bcount)); + a = (ma ? stbi__shiftsigned(v & ma, ashift, acount) : 255); + all_a |= a; + if (target == 4) out[z++] = STBI__BYTECAST(a); + } + } + stbi__skip(s, pad); + } + } + + // if alpha channel is all 0s, replace with all 255s + if (target == 4 && all_a == 0) + for (i=4*s->img_x*s->img_y-1; i >= 0; i -= 4) + out[i] = 255; + + if (flip_vertically) { + stbi_uc t; + for (j=0; j < (int) s->img_y>>1; ++j) { + stbi_uc *p1 = out + j *s->img_x*target; + stbi_uc *p2 = out + (s->img_y-1-j)*s->img_x*target; + for (i=0; i < (int) s->img_x*target; ++i) { + t = p1[i]; p1[i] = p2[i]; p2[i] = t; + } + } + } + + if (req_comp && req_comp != target) { + out = stbi__convert_format(out, target, req_comp, s->img_x, s->img_y); + if (out == NULL) return out; // stbi__convert_format frees input on failure + } + + *x = s->img_x; + *y = s->img_y; + if (comp) *comp = s->img_n; + return out; +} +#endif + +// Targa Truevision - TGA +// by Jonathan Dummer +#ifndef STBI_NO_TGA +// returns STBI_rgb or whatever, 0 on error +static int stbi__tga_get_comp(int bits_per_pixel, int is_grey, int* is_rgb16) +{ + // only RGB or RGBA (incl. 16bit) or grey allowed + if (is_rgb16) *is_rgb16 = 0; + switch(bits_per_pixel) { + case 8: return STBI_grey; + case 16: if(is_grey) return STBI_grey_alpha; + // fallthrough + case 15: if(is_rgb16) *is_rgb16 = 1; + return STBI_rgb; + case 24: // fallthrough + case 32: return bits_per_pixel/8; + default: return 0; + } +} + +static int stbi__tga_info(stbi__context *s, int *x, int *y, int *comp) +{ + int tga_w, tga_h, tga_comp, tga_image_type, tga_bits_per_pixel, tga_colormap_bpp; + int sz, tga_colormap_type; + stbi__get8(s); // discard Offset + tga_colormap_type = stbi__get8(s); // colormap type + if( tga_colormap_type > 1 ) { + stbi__rewind(s); + return 0; // only RGB or indexed allowed + } + tga_image_type = stbi__get8(s); // image type + if ( tga_colormap_type == 1 ) { // colormapped (paletted) image + if (tga_image_type != 1 && tga_image_type != 9) { + stbi__rewind(s); + return 0; + } + stbi__skip(s,4); // skip index of first colormap entry and number of entries + sz = stbi__get8(s); // check bits per palette color entry + if ( (sz != 8) && (sz != 15) && (sz != 16) && (sz != 24) && (sz != 32) ) { + stbi__rewind(s); + return 0; + } + stbi__skip(s,4); // skip image x and y origin + tga_colormap_bpp = sz; + } else { // "normal" image w/o colormap - only RGB or grey allowed, +/- RLE + if ( (tga_image_type != 2) && (tga_image_type != 3) && (tga_image_type != 10) && (tga_image_type != 11) ) { + stbi__rewind(s); + return 0; // only RGB or grey allowed, +/- RLE + } + stbi__skip(s,9); // skip colormap specification and image x/y origin + tga_colormap_bpp = 0; + } + tga_w = stbi__get16le(s); + if( tga_w < 1 ) { + stbi__rewind(s); + return 0; // test width + } + tga_h = stbi__get16le(s); + if( tga_h < 1 ) { + stbi__rewind(s); + return 0; // test height + } + tga_bits_per_pixel = stbi__get8(s); // bits per pixel + stbi__get8(s); // ignore alpha bits + if (tga_colormap_bpp != 0) { + if((tga_bits_per_pixel != 8) && (tga_bits_per_pixel != 16)) { + // when using a colormap, tga_bits_per_pixel is the size of the indexes + // I don't think anything but 8 or 16bit indexes makes sense + stbi__rewind(s); + return 0; + } + tga_comp = stbi__tga_get_comp(tga_colormap_bpp, 0, NULL); + } else { + tga_comp = stbi__tga_get_comp(tga_bits_per_pixel, (tga_image_type == 3) || (tga_image_type == 11), NULL); + } + if(!tga_comp) { + stbi__rewind(s); + return 0; + } + if (x) *x = tga_w; + if (y) *y = tga_h; + if (comp) *comp = tga_comp; + return 1; // seems to have passed everything +} + +static int stbi__tga_test(stbi__context *s) +{ + int res = 0; + int sz, tga_color_type; + stbi__get8(s); // discard Offset + tga_color_type = stbi__get8(s); // color type + if ( tga_color_type > 1 ) goto errorEnd; // only RGB or indexed allowed + sz = stbi__get8(s); // image type + if ( tga_color_type == 1 ) { // colormapped (paletted) image + if (sz != 1 && sz != 9) goto errorEnd; // colortype 1 demands image type 1 or 9 + stbi__skip(s,4); // skip index of first colormap entry and number of entries + sz = stbi__get8(s); // check bits per palette color entry + if ( (sz != 8) && (sz != 15) && (sz != 16) && (sz != 24) && (sz != 32) ) goto errorEnd; + stbi__skip(s,4); // skip image x and y origin + } else { // "normal" image w/o colormap + if ( (sz != 2) && (sz != 3) && (sz != 10) && (sz != 11) ) goto errorEnd; // only RGB or grey allowed, +/- RLE + stbi__skip(s,9); // skip colormap specification and image x/y origin + } + if ( stbi__get16le(s) < 1 ) goto errorEnd; // test width + if ( stbi__get16le(s) < 1 ) goto errorEnd; // test height + sz = stbi__get8(s); // bits per pixel + if ( (tga_color_type == 1) && (sz != 8) && (sz != 16) ) goto errorEnd; // for colormapped images, bpp is size of an index + if ( (sz != 8) && (sz != 15) && (sz != 16) && (sz != 24) && (sz != 32) ) goto errorEnd; + + res = 1; // if we got this far, everything's good and we can return 1 instead of 0 + +errorEnd: + stbi__rewind(s); + return res; +} + +// read 16bit value and convert to 24bit RGB +static void stbi__tga_read_rgb16(stbi__context *s, stbi_uc* out) +{ + stbi__uint16 px = (stbi__uint16)stbi__get16le(s); + stbi__uint16 fiveBitMask = 31; + // we have 3 channels with 5bits each + int r = (px >> 10) & fiveBitMask; + int g = (px >> 5) & fiveBitMask; + int b = px & fiveBitMask; + // Note that this saves the data in RGB(A) order, so it doesn't need to be swapped later + out[0] = (stbi_uc)((r * 255)/31); + out[1] = (stbi_uc)((g * 255)/31); + out[2] = (stbi_uc)((b * 255)/31); + + // some people claim that the most significant bit might be used for alpha + // (possibly if an alpha-bit is set in the "image descriptor byte") + // but that only made 16bit test images completely translucent.. + // so let's treat all 15 and 16bit TGAs as RGB with no alpha. +} + +static void *stbi__tga_load(stbi__context *s, int *x, int *y, int *comp, int req_comp, stbi__result_info *ri) +{ + // read in the TGA header stuff + int tga_offset = stbi__get8(s); + int tga_indexed = stbi__get8(s); + int tga_image_type = stbi__get8(s); + int tga_is_RLE = 0; + int tga_palette_start = stbi__get16le(s); + int tga_palette_len = stbi__get16le(s); + int tga_palette_bits = stbi__get8(s); + int tga_x_origin = stbi__get16le(s); + int tga_y_origin = stbi__get16le(s); + int tga_width = stbi__get16le(s); + int tga_height = stbi__get16le(s); + int tga_bits_per_pixel = stbi__get8(s); + int tga_comp, tga_rgb16=0; + int tga_inverted = stbi__get8(s); + // int tga_alpha_bits = tga_inverted & 15; // the 4 lowest bits - unused (useless?) + // image data + unsigned char *tga_data; + unsigned char *tga_palette = NULL; + int i, j; + unsigned char raw_data[4] = {0}; + int RLE_count = 0; + int RLE_repeating = 0; + int read_next_pixel = 1; + STBI_NOTUSED(ri); + STBI_NOTUSED(tga_x_origin); // @TODO + STBI_NOTUSED(tga_y_origin); // @TODO + + // do a tiny bit of precessing + if ( tga_image_type >= 8 ) + { + tga_image_type -= 8; + tga_is_RLE = 1; + } + tga_inverted = 1 - ((tga_inverted >> 5) & 1); + + // If I'm paletted, then I'll use the number of bits from the palette + if ( tga_indexed ) tga_comp = stbi__tga_get_comp(tga_palette_bits, 0, &tga_rgb16); + else tga_comp = stbi__tga_get_comp(tga_bits_per_pixel, (tga_image_type == 3), &tga_rgb16); + + if(!tga_comp) // shouldn't really happen, stbi__tga_test() should have ensured basic consistency + return stbi__errpuc("bad format", "Can't find out TGA pixelformat"); + + // tga info + *x = tga_width; + *y = tga_height; + if (comp) *comp = tga_comp; + + if (!stbi__mad3sizes_valid(tga_width, tga_height, tga_comp, 0)) + return stbi__errpuc("too large", "Corrupt TGA"); + + tga_data = (unsigned char*)stbi__malloc_mad3(tga_width, tga_height, tga_comp, 0); + if (!tga_data) return stbi__errpuc("outofmem", "Out of memory"); + + // skip to the data's starting position (offset usually = 0) + stbi__skip(s, tga_offset ); + + if ( !tga_indexed && !tga_is_RLE && !tga_rgb16 ) { + for (i=0; i < tga_height; ++i) { + int row = tga_inverted ? tga_height -i - 1 : i; + stbi_uc *tga_row = tga_data + row*tga_width*tga_comp; + stbi__getn(s, tga_row, tga_width * tga_comp); + } + } else { + // do I need to load a palette? + if ( tga_indexed) + { + // any data to skip? (offset usually = 0) + stbi__skip(s, tga_palette_start ); + // load the palette + tga_palette = (unsigned char*)stbi__malloc_mad2(tga_palette_len, tga_comp, 0); + if (!tga_palette) { + STBI_FREE(tga_data); + return stbi__errpuc("outofmem", "Out of memory"); + } + if (tga_rgb16) { + stbi_uc *pal_entry = tga_palette; + STBI_ASSERT(tga_comp == STBI_rgb); + for (i=0; i < tga_palette_len; ++i) { + stbi__tga_read_rgb16(s, pal_entry); + pal_entry += tga_comp; + } + } else if (!stbi__getn(s, tga_palette, tga_palette_len * tga_comp)) { + STBI_FREE(tga_data); + STBI_FREE(tga_palette); + return stbi__errpuc("bad palette", "Corrupt TGA"); + } + } + // load the data + for (i=0; i < tga_width * tga_height; ++i) + { + // if I'm in RLE mode, do I need to get a RLE stbi__pngchunk? + if ( tga_is_RLE ) + { + if ( RLE_count == 0 ) + { + // yep, get the next byte as a RLE command + int RLE_cmd = stbi__get8(s); + RLE_count = 1 + (RLE_cmd & 127); + RLE_repeating = RLE_cmd >> 7; + read_next_pixel = 1; + } else if ( !RLE_repeating ) + { + read_next_pixel = 1; + } + } else + { + read_next_pixel = 1; + } + // OK, if I need to read a pixel, do it now + if ( read_next_pixel ) + { + // load however much data we did have + if ( tga_indexed ) + { + // read in index, then perform the lookup + int pal_idx = (tga_bits_per_pixel == 8) ? stbi__get8(s) : stbi__get16le(s); + if ( pal_idx >= tga_palette_len ) { + // invalid index + pal_idx = 0; + } + pal_idx *= tga_comp; + for (j = 0; j < tga_comp; ++j) { + raw_data[j] = tga_palette[pal_idx+j]; + } + } else if(tga_rgb16) { + STBI_ASSERT(tga_comp == STBI_rgb); + stbi__tga_read_rgb16(s, raw_data); + } else { + // read in the data raw + for (j = 0; j < tga_comp; ++j) { + raw_data[j] = stbi__get8(s); + } + } + // clear the reading flag for the next pixel + read_next_pixel = 0; + } // end of reading a pixel + + // copy data + for (j = 0; j < tga_comp; ++j) + tga_data[i*tga_comp+j] = raw_data[j]; + + // in case we're in RLE mode, keep counting down + --RLE_count; + } + // do I need to invert the image? + if ( tga_inverted ) + { + for (j = 0; j*2 < tga_height; ++j) + { + int index1 = j * tga_width * tga_comp; + int index2 = (tga_height - 1 - j) * tga_width * tga_comp; + for (i = tga_width * tga_comp; i > 0; --i) + { + unsigned char temp = tga_data[index1]; + tga_data[index1] = tga_data[index2]; + tga_data[index2] = temp; + ++index1; + ++index2; + } + } + } + // clear my palette, if I had one + if ( tga_palette != NULL ) + { + STBI_FREE( tga_palette ); + } + } + + // swap RGB - if the source data was RGB16, it already is in the right order + if (tga_comp >= 3 && !tga_rgb16) + { + unsigned char* tga_pixel = tga_data; + for (i=0; i < tga_width * tga_height; ++i) + { + unsigned char temp = tga_pixel[0]; + tga_pixel[0] = tga_pixel[2]; + tga_pixel[2] = temp; + tga_pixel += tga_comp; + } + } + + // convert to target component count + if (req_comp && req_comp != tga_comp) + tga_data = stbi__convert_format(tga_data, tga_comp, req_comp, tga_width, tga_height); + + // the things I do to get rid of an error message, and yet keep + // Microsoft's C compilers happy... [8^( + tga_palette_start = tga_palette_len = tga_palette_bits = + tga_x_origin = tga_y_origin = 0; + STBI_NOTUSED(tga_palette_start); + // OK, done + return tga_data; +} +#endif + +// ************************************************************************************************* +// Photoshop PSD loader -- PD by Thatcher Ulrich, integration by Nicolas Schulz, tweaked by STB + +#ifndef STBI_NO_PSD +static int stbi__psd_test(stbi__context *s) +{ + int r = (stbi__get32be(s) == 0x38425053); + stbi__rewind(s); + return r; +} + +static int stbi__psd_decode_rle(stbi__context *s, stbi_uc *p, int pixelCount) +{ + int count, nleft, len; + + count = 0; + while ((nleft = pixelCount - count) > 0) { + len = stbi__get8(s); + if (len == 128) { + // No-op. + } else if (len < 128) { + // Copy next len+1 bytes literally. + len++; + if (len > nleft) return 0; // corrupt data + count += len; + while (len) { + *p = stbi__get8(s); + p += 4; + len--; + } + } else if (len > 128) { + stbi_uc val; + // Next -len+1 bytes in the dest are replicated from next source byte. + // (Interpret len as a negative 8-bit int.) + len = 257 - len; + if (len > nleft) return 0; // corrupt data + val = stbi__get8(s); + count += len; + while (len) { + *p = val; + p += 4; + len--; + } + } + } + + return 1; +} + +static void *stbi__psd_load(stbi__context *s, int *x, int *y, int *comp, int req_comp, stbi__result_info *ri, int bpc) +{ + int pixelCount; + int channelCount, compression; + int channel, i; + int bitdepth; + int w,h; + stbi_uc *out; + STBI_NOTUSED(ri); + + // Check identifier + if (stbi__get32be(s) != 0x38425053) // "8BPS" + return stbi__errpuc("not PSD", "Corrupt PSD image"); + + // Check file type version. + if (stbi__get16be(s) != 1) + return stbi__errpuc("wrong version", "Unsupported version of PSD image"); + + // Skip 6 reserved bytes. + stbi__skip(s, 6 ); + + // Read the number of channels (R, G, B, A, etc). + channelCount = stbi__get16be(s); + if (channelCount < 0 || channelCount > 16) + return stbi__errpuc("wrong channel count", "Unsupported number of channels in PSD image"); + + // Read the rows and columns of the image. + h = stbi__get32be(s); + w = stbi__get32be(s); + + // Make sure the depth is 8 bits. + bitdepth = stbi__get16be(s); + if (bitdepth != 8 && bitdepth != 16) + return stbi__errpuc("unsupported bit depth", "PSD bit depth is not 8 or 16 bit"); + + // Make sure the color mode is RGB. + // Valid options are: + // 0: Bitmap + // 1: Grayscale + // 2: Indexed color + // 3: RGB color + // 4: CMYK color + // 7: Multichannel + // 8: Duotone + // 9: Lab color + if (stbi__get16be(s) != 3) + return stbi__errpuc("wrong color format", "PSD is not in RGB color format"); + + // Skip the Mode Data. (It's the palette for indexed color; other info for other modes.) + stbi__skip(s,stbi__get32be(s) ); + + // Skip the image resources. (resolution, pen tool paths, etc) + stbi__skip(s, stbi__get32be(s) ); + + // Skip the reserved data. + stbi__skip(s, stbi__get32be(s) ); + + // Find out if the data is compressed. + // Known values: + // 0: no compression + // 1: RLE compressed + compression = stbi__get16be(s); + if (compression > 1) + return stbi__errpuc("bad compression", "PSD has an unknown compression format"); + + // Check size + if (!stbi__mad3sizes_valid(4, w, h, 0)) + return stbi__errpuc("too large", "Corrupt PSD"); + + // Create the destination image. + + if (!compression && bitdepth == 16 && bpc == 16) { + out = (stbi_uc *) stbi__malloc_mad3(8, w, h, 0); + ri->bits_per_channel = 16; + } else + out = (stbi_uc *) stbi__malloc(4 * w*h); + + if (!out) return stbi__errpuc("outofmem", "Out of memory"); + pixelCount = w*h; + + // Initialize the data to zero. + //memset( out, 0, pixelCount * 4 ); + + // Finally, the image data. + if (compression) { + // RLE as used by .PSD and .TIFF + // Loop until you get the number of unpacked bytes you are expecting: + // Read the next source byte into n. + // If n is between 0 and 127 inclusive, copy the next n+1 bytes literally. + // Else if n is between -127 and -1 inclusive, copy the next byte -n+1 times. + // Else if n is 128, noop. + // Endloop + + // The RLE-compressed data is preceded by a 2-byte data count for each row in the data, + // which we're going to just skip. + stbi__skip(s, h * channelCount * 2 ); + + // Read the RLE data by channel. + for (channel = 0; channel < 4; channel++) { + stbi_uc *p; + + p = out+channel; + if (channel >= channelCount) { + // Fill this channel with default data. + for (i = 0; i < pixelCount; i++, p += 4) + *p = (channel == 3 ? 255 : 0); + } else { + // Read the RLE data. + if (!stbi__psd_decode_rle(s, p, pixelCount)) { + STBI_FREE(out); + return stbi__errpuc("corrupt", "bad RLE data"); + } + } + } + + } else { + // We're at the raw image data. It's each channel in order (Red, Green, Blue, Alpha, ...) + // where each channel consists of an 8-bit (or 16-bit) value for each pixel in the image. + + // Read the data by channel. + for (channel = 0; channel < 4; channel++) { + if (channel >= channelCount) { + // Fill this channel with default data. + if (bitdepth == 16 && bpc == 16) { + stbi__uint16 *q = ((stbi__uint16 *) out) + channel; + stbi__uint16 val = channel == 3 ? 65535 : 0; + for (i = 0; i < pixelCount; i++, q += 4) + *q = val; + } else { + stbi_uc *p = out+channel; + stbi_uc val = channel == 3 ? 255 : 0; + for (i = 0; i < pixelCount; i++, p += 4) + *p = val; + } + } else { + if (ri->bits_per_channel == 16) { // output bpc + stbi__uint16 *q = ((stbi__uint16 *) out) + channel; + for (i = 0; i < pixelCount; i++, q += 4) + *q = (stbi__uint16) stbi__get16be(s); + } else { + stbi_uc *p = out+channel; + if (bitdepth == 16) { // input bpc + for (i = 0; i < pixelCount; i++, p += 4) + *p = (stbi_uc) (stbi__get16be(s) >> 8); + } else { + for (i = 0; i < pixelCount; i++, p += 4) + *p = stbi__get8(s); + } + } + } + } + } + + // remove weird white matte from PSD + if (channelCount >= 4) { + if (ri->bits_per_channel == 16) { + for (i=0; i < w*h; ++i) { + stbi__uint16 *pixel = (stbi__uint16 *) out + 4*i; + if (pixel[3] != 0 && pixel[3] != 65535) { + float a = pixel[3] / 65535.0f; + float ra = 1.0f / a; + float inv_a = 65535.0f * (1 - ra); + pixel[0] = (stbi__uint16) (pixel[0]*ra + inv_a); + pixel[1] = (stbi__uint16) (pixel[1]*ra + inv_a); + pixel[2] = (stbi__uint16) (pixel[2]*ra + inv_a); + } + } + } else { + for (i=0; i < w*h; ++i) { + unsigned char *pixel = out + 4*i; + if (pixel[3] != 0 && pixel[3] != 255) { + float a = pixel[3] / 255.0f; + float ra = 1.0f / a; + float inv_a = 255.0f * (1 - ra); + pixel[0] = (unsigned char) (pixel[0]*ra + inv_a); + pixel[1] = (unsigned char) (pixel[1]*ra + inv_a); + pixel[2] = (unsigned char) (pixel[2]*ra + inv_a); + } + } + } + } + + // convert to desired output format + if (req_comp && req_comp != 4) { + if (ri->bits_per_channel == 16) + out = (stbi_uc *) stbi__convert_format16((stbi__uint16 *) out, 4, req_comp, w, h); + else + out = stbi__convert_format(out, 4, req_comp, w, h); + if (out == NULL) return out; // stbi__convert_format frees input on failure + } + + if (comp) *comp = 4; + *y = h; + *x = w; + + return out; +} +#endif + +// ************************************************************************************************* +// Softimage PIC loader +// by Tom Seddon +// +// See http://softimage.wiki.softimage.com/index.php/INFO:_PIC_file_format +// See http://ozviz.wasp.uwa.edu.au/~pbourke/dataformats/softimagepic/ + +#ifndef STBI_NO_PIC +static int stbi__pic_is4(stbi__context *s,const char *str) +{ + int i; + for (i=0; i<4; ++i) + if (stbi__get8(s) != (stbi_uc)str[i]) + return 0; + + return 1; +} + +static int stbi__pic_test_core(stbi__context *s) +{ + int i; + + if (!stbi__pic_is4(s,"\x53\x80\xF6\x34")) + return 0; + + for(i=0;i<84;++i) + stbi__get8(s); + + if (!stbi__pic_is4(s,"PICT")) + return 0; + + return 1; +} + +typedef struct +{ + stbi_uc size,type,channel; +} stbi__pic_packet; + +static stbi_uc *stbi__readval(stbi__context *s, int channel, stbi_uc *dest) +{ + int mask=0x80, i; + + for (i=0; i<4; ++i, mask>>=1) { + if (channel & mask) { + if (stbi__at_eof(s)) return stbi__errpuc("bad file","PIC file too short"); + dest[i]=stbi__get8(s); + } + } + + return dest; +} + +static void stbi__copyval(int channel,stbi_uc *dest,const stbi_uc *src) +{ + int mask=0x80,i; + + for (i=0;i<4; ++i, mask>>=1) + if (channel&mask) + dest[i]=src[i]; +} + +static stbi_uc *stbi__pic_load_core(stbi__context *s,int width,int height,int *comp, stbi_uc *result) +{ + int act_comp=0,num_packets=0,y,chained; + stbi__pic_packet packets[10]; + + // this will (should...) cater for even some bizarre stuff like having data + // for the same channel in multiple packets. + do { + stbi__pic_packet *packet; + + if (num_packets==sizeof(packets)/sizeof(packets[0])) + return stbi__errpuc("bad format","too many packets"); + + packet = &packets[num_packets++]; + + chained = stbi__get8(s); + packet->size = stbi__get8(s); + packet->type = stbi__get8(s); + packet->channel = stbi__get8(s); + + act_comp |= packet->channel; + + if (stbi__at_eof(s)) return stbi__errpuc("bad file","file too short (reading packets)"); + if (packet->size != 8) return stbi__errpuc("bad format","packet isn't 8bpp"); + } while (chained); + + *comp = (act_comp & 0x10 ? 4 : 3); // has alpha channel? + + for(y=0; ytype) { + default: + return stbi__errpuc("bad format","packet has bad compression type"); + + case 0: {//uncompressed + int x; + + for(x=0;xchannel,dest)) + return 0; + break; + } + + case 1://Pure RLE + { + int left=width, i; + + while (left>0) { + stbi_uc count,value[4]; + + count=stbi__get8(s); + if (stbi__at_eof(s)) return stbi__errpuc("bad file","file too short (pure read count)"); + + if (count > left) + count = (stbi_uc) left; + + if (!stbi__readval(s,packet->channel,value)) return 0; + + for(i=0; ichannel,dest,value); + left -= count; + } + } + break; + + case 2: {//Mixed RLE + int left=width; + while (left>0) { + int count = stbi__get8(s), i; + if (stbi__at_eof(s)) return stbi__errpuc("bad file","file too short (mixed read count)"); + + if (count >= 128) { // Repeated + stbi_uc value[4]; + + if (count==128) + count = stbi__get16be(s); + else + count -= 127; + if (count > left) + return stbi__errpuc("bad file","scanline overrun"); + + if (!stbi__readval(s,packet->channel,value)) + return 0; + + for(i=0;ichannel,dest,value); + } else { // Raw + ++count; + if (count>left) return stbi__errpuc("bad file","scanline overrun"); + + for(i=0;ichannel,dest)) + return 0; + } + left-=count; + } + break; + } + } + } + } + + return result; +} + +static void *stbi__pic_load(stbi__context *s,int *px,int *py,int *comp,int req_comp, stbi__result_info *ri) +{ + stbi_uc *result; + int i, x,y, internal_comp; + STBI_NOTUSED(ri); + + if (!comp) comp = &internal_comp; + + for (i=0; i<92; ++i) + stbi__get8(s); + + x = stbi__get16be(s); + y = stbi__get16be(s); + if (stbi__at_eof(s)) return stbi__errpuc("bad file","file too short (pic header)"); + if (!stbi__mad3sizes_valid(x, y, 4, 0)) return stbi__errpuc("too large", "PIC image too large to decode"); + + stbi__get32be(s); //skip `ratio' + stbi__get16be(s); //skip `fields' + stbi__get16be(s); //skip `pad' + + // intermediate buffer is RGBA + result = (stbi_uc *) stbi__malloc_mad3(x, y, 4, 0); + memset(result, 0xff, x*y*4); + + if (!stbi__pic_load_core(s,x,y,comp, result)) { + STBI_FREE(result); + result=0; + } + *px = x; + *py = y; + if (req_comp == 0) req_comp = *comp; + result=stbi__convert_format(result,4,req_comp,x,y); + + return result; +} + +static int stbi__pic_test(stbi__context *s) +{ + int r = stbi__pic_test_core(s); + stbi__rewind(s); + return r; +} +#endif + +// ************************************************************************************************* +// GIF loader -- public domain by Jean-Marc Lienher -- simplified/shrunk by stb + +#ifndef STBI_NO_GIF +typedef struct +{ + stbi__int16 prefix; + stbi_uc first; + stbi_uc suffix; +} stbi__gif_lzw; + +typedef struct +{ + int w,h; + stbi_uc *out; // output buffer (always 4 components) + stbi_uc *background; // The current "background" as far as a gif is concerned + stbi_uc *history; + int flags, bgindex, ratio, transparent, eflags; + stbi_uc pal[256][4]; + stbi_uc lpal[256][4]; + stbi__gif_lzw codes[8192]; + stbi_uc *color_table; + int parse, step; + int lflags; + int start_x, start_y; + int max_x, max_y; + int cur_x, cur_y; + int line_size; + int delay; +} stbi__gif; + +static int stbi__gif_test_raw(stbi__context *s) +{ + int sz; + if (stbi__get8(s) != 'G' || stbi__get8(s) != 'I' || stbi__get8(s) != 'F' || stbi__get8(s) != '8') return 0; + sz = stbi__get8(s); + if (sz != '9' && sz != '7') return 0; + if (stbi__get8(s) != 'a') return 0; + return 1; +} + +static int stbi__gif_test(stbi__context *s) +{ + int r = stbi__gif_test_raw(s); + stbi__rewind(s); + return r; +} + +static void stbi__gif_parse_colortable(stbi__context *s, stbi_uc pal[256][4], int num_entries, int transp) +{ + int i; + for (i=0; i < num_entries; ++i) { + pal[i][2] = stbi__get8(s); + pal[i][1] = stbi__get8(s); + pal[i][0] = stbi__get8(s); + pal[i][3] = transp == i ? 0 : 255; + } +} + +static int stbi__gif_header(stbi__context *s, stbi__gif *g, int *comp, int is_info) +{ + stbi_uc version; + if (stbi__get8(s) != 'G' || stbi__get8(s) != 'I' || stbi__get8(s) != 'F' || stbi__get8(s) != '8') + return stbi__err("not GIF", "Corrupt GIF"); + + version = stbi__get8(s); + if (version != '7' && version != '9') return stbi__err("not GIF", "Corrupt GIF"); + if (stbi__get8(s) != 'a') return stbi__err("not GIF", "Corrupt GIF"); + + stbi__g_failure_reason = ""; + g->w = stbi__get16le(s); + g->h = stbi__get16le(s); + g->flags = stbi__get8(s); + g->bgindex = stbi__get8(s); + g->ratio = stbi__get8(s); + g->transparent = -1; + + if (comp != 0) *comp = 4; // can't actually tell whether it's 3 or 4 until we parse the comments + + if (is_info) return 1; + + if (g->flags & 0x80) + stbi__gif_parse_colortable(s,g->pal, 2 << (g->flags & 7), -1); + + return 1; +} + +static int stbi__gif_info_raw(stbi__context *s, int *x, int *y, int *comp) +{ + stbi__gif* g = (stbi__gif*) stbi__malloc(sizeof(stbi__gif)); + if (!stbi__gif_header(s, g, comp, 1)) { + STBI_FREE(g); + stbi__rewind( s ); + return 0; + } + if (x) *x = g->w; + if (y) *y = g->h; + STBI_FREE(g); + return 1; +} + +static void stbi__out_gif_code(stbi__gif *g, stbi__uint16 code) +{ + stbi_uc *p, *c; + int idx; + + // recurse to decode the prefixes, since the linked-list is backwards, + // and working backwards through an interleaved image would be nasty + if (g->codes[code].prefix >= 0) + stbi__out_gif_code(g, g->codes[code].prefix); + + if (g->cur_y >= g->max_y) return; + + idx = g->cur_x + g->cur_y; + p = &g->out[idx]; + g->history[idx / 4] = 1; + + c = &g->color_table[g->codes[code].suffix * 4]; + if (c[3] > 128) { // don't render transparent pixels; + p[0] = c[2]; + p[1] = c[1]; + p[2] = c[0]; + p[3] = c[3]; + } + g->cur_x += 4; + + if (g->cur_x >= g->max_x) { + g->cur_x = g->start_x; + g->cur_y += g->step; + + while (g->cur_y >= g->max_y && g->parse > 0) { + g->step = (1 << g->parse) * g->line_size; + g->cur_y = g->start_y + (g->step >> 1); + --g->parse; + } + } +} + +static stbi_uc *stbi__process_gif_raster(stbi__context *s, stbi__gif *g) +{ + stbi_uc lzw_cs; + stbi__int32 len, init_code; + stbi__uint32 first; + stbi__int32 codesize, codemask, avail, oldcode, bits, valid_bits, clear; + stbi__gif_lzw *p; + + lzw_cs = stbi__get8(s); + if (lzw_cs > 12) return NULL; + clear = 1 << lzw_cs; + first = 1; + codesize = lzw_cs + 1; + codemask = (1 << codesize) - 1; + bits = 0; + valid_bits = 0; + for (init_code = 0; init_code < clear; init_code++) { + g->codes[init_code].prefix = -1; + g->codes[init_code].first = (stbi_uc) init_code; + g->codes[init_code].suffix = (stbi_uc) init_code; + } + + // support no starting clear code + avail = clear+2; + oldcode = -1; + + len = 0; + for(;;) { + if (valid_bits < codesize) { + if (len == 0) { + len = stbi__get8(s); // start new block + if (len == 0) + return g->out; + } + --len; + bits |= (stbi__int32) stbi__get8(s) << valid_bits; + valid_bits += 8; + } else { + stbi__int32 code = bits & codemask; + bits >>= codesize; + valid_bits -= codesize; + // @OPTIMIZE: is there some way we can accelerate the non-clear path? + if (code == clear) { // clear code + codesize = lzw_cs + 1; + codemask = (1 << codesize) - 1; + avail = clear + 2; + oldcode = -1; + first = 0; + } else if (code == clear + 1) { // end of stream code + stbi__skip(s, len); + while ((len = stbi__get8(s)) > 0) + stbi__skip(s,len); + return g->out; + } else if (code <= avail) { + if (first) { + return stbi__errpuc("no clear code", "Corrupt GIF"); + } + + if (oldcode >= 0) { + p = &g->codes[avail++]; + if (avail > 8192) { + return stbi__errpuc("too many codes", "Corrupt GIF"); + } + + p->prefix = (stbi__int16) oldcode; + p->first = g->codes[oldcode].first; + p->suffix = (code == avail) ? p->first : g->codes[code].first; + } else if (code == avail) + return stbi__errpuc("illegal code in raster", "Corrupt GIF"); + + stbi__out_gif_code(g, (stbi__uint16) code); + + if ((avail & codemask) == 0 && avail <= 0x0FFF) { + codesize++; + codemask = (1 << codesize) - 1; + } + + oldcode = code; + } else { + return stbi__errpuc("illegal code in raster", "Corrupt GIF"); + } + } + } +} + +// this function is designed to support animated gifs, although stb_image doesn't support it +// two back is the image from two frames ago, used for a very specific disposal format +static stbi_uc *stbi__gif_load_next(stbi__context *s, stbi__gif *g, int *comp, int req_comp, stbi_uc *two_back) +{ + int dispose; + int first_frame; + int pi; + int pcount; + STBI_NOTUSED(req_comp); + + // on first frame, any non-written pixels get the background colour (non-transparent) + first_frame = 0; + if (g->out == 0) { + if (!stbi__gif_header(s, g, comp,0)) return 0; // stbi__g_failure_reason set by stbi__gif_header + if (!stbi__mad3sizes_valid(4, g->w, g->h, 0)) + return stbi__errpuc("too large", "GIF image is too large"); + pcount = g->w * g->h; + g->out = (stbi_uc *) stbi__malloc(4 * pcount); + g->background = (stbi_uc *) stbi__malloc(4 * pcount); + g->history = (stbi_uc *) stbi__malloc(pcount); + if (!g->out || !g->background || !g->history) + return stbi__errpuc("outofmem", "Out of memory"); + + // image is treated as "transparent" at the start - ie, nothing overwrites the current background; + // background colour is only used for pixels that are not rendered first frame, after that "background" + // color refers to the color that was there the previous frame. + memset(g->out, 0x00, 4 * pcount); + memset(g->background, 0x00, 4 * pcount); // state of the background (starts transparent) + memset(g->history, 0x00, pcount); // pixels that were affected previous frame + first_frame = 1; + } else { + // second frame - how do we dispoase of the previous one? + dispose = (g->eflags & 0x1C) >> 2; + pcount = g->w * g->h; + + if ((dispose == 3) && (two_back == 0)) { + dispose = 2; // if I don't have an image to revert back to, default to the old background + } + + if (dispose == 3) { // use previous graphic + for (pi = 0; pi < pcount; ++pi) { + if (g->history[pi]) { + memcpy( &g->out[pi * 4], &two_back[pi * 4], 4 ); + } + } + } else if (dispose == 2) { + // restore what was changed last frame to background before that frame; + for (pi = 0; pi < pcount; ++pi) { + if (g->history[pi]) { + memcpy( &g->out[pi * 4], &g->background[pi * 4], 4 ); + } + } + } else { + // This is a non-disposal case eithe way, so just + // leave the pixels as is, and they will become the new background + // 1: do not dispose + // 0: not specified. + } + + // background is what out is after the undoing of the previou frame; + memcpy( g->background, g->out, 4 * g->w * g->h ); + } + + // clear my history; + memset( g->history, 0x00, g->w * g->h ); // pixels that were affected previous frame + + for (;;) { + int tag = stbi__get8(s); + switch (tag) { + case 0x2C: /* Image Descriptor */ + { + stbi__int32 x, y, w, h; + stbi_uc *o; + + x = stbi__get16le(s); + y = stbi__get16le(s); + w = stbi__get16le(s); + h = stbi__get16le(s); + if (((x + w) > (g->w)) || ((y + h) > (g->h))) + return stbi__errpuc("bad Image Descriptor", "Corrupt GIF"); + + g->line_size = g->w * 4; + g->start_x = x * 4; + g->start_y = y * g->line_size; + g->max_x = g->start_x + w * 4; + g->max_y = g->start_y + h * g->line_size; + g->cur_x = g->start_x; + g->cur_y = g->start_y; + + // if the width of the specified rectangle is 0, that means + // we may not see *any* pixels or the image is malformed; + // to make sure this is caught, move the current y down to + // max_y (which is what out_gif_code checks). + if (w == 0) + g->cur_y = g->max_y; + + g->lflags = stbi__get8(s); + + if (g->lflags & 0x40) { + g->step = 8 * g->line_size; // first interlaced spacing + g->parse = 3; + } else { + g->step = g->line_size; + g->parse = 0; + } + + if (g->lflags & 0x80) { + stbi__gif_parse_colortable(s,g->lpal, 2 << (g->lflags & 7), g->eflags & 0x01 ? g->transparent : -1); + g->color_table = (stbi_uc *) g->lpal; + } else if (g->flags & 0x80) { + g->color_table = (stbi_uc *) g->pal; + } else + return stbi__errpuc("missing color table", "Corrupt GIF"); + + o = stbi__process_gif_raster(s, g); + if (!o) return NULL; + + // if this was the first frame, + pcount = g->w * g->h; + if (first_frame && (g->bgindex > 0)) { + // if first frame, any pixel not drawn to gets the background color + for (pi = 0; pi < pcount; ++pi) { + if (g->history[pi] == 0) { + g->pal[g->bgindex][3] = 255; // just in case it was made transparent, undo that; It will be reset next frame if need be; + memcpy( &g->out[pi * 4], &g->pal[g->bgindex], 4 ); + } + } + } + + return o; + } + + case 0x21: // Comment Extension. + { + int len; + int ext = stbi__get8(s); + if (ext == 0xF9) { // Graphic Control Extension. + len = stbi__get8(s); + if (len == 4) { + g->eflags = stbi__get8(s); + g->delay = 10 * stbi__get16le(s); // delay - 1/100th of a second, saving as 1/1000ths. + + // unset old transparent + if (g->transparent >= 0) { + g->pal[g->transparent][3] = 255; + } + if (g->eflags & 0x01) { + g->transparent = stbi__get8(s); + if (g->transparent >= 0) { + g->pal[g->transparent][3] = 0; + } + } else { + // don't need transparent + stbi__skip(s, 1); + g->transparent = -1; + } + } else { + stbi__skip(s, len); + break; + } + } + while ((len = stbi__get8(s)) != 0) { + stbi__skip(s, len); + } + break; + } + + case 0x3B: // gif stream termination code + return (stbi_uc *) s; // using '1' causes warning on some compilers + + default: + return stbi__errpuc("unknown code", "Corrupt GIF"); + } + } +} + +static void *stbi__load_gif_main(stbi__context *s, int **delays, int *x, int *y, int *z, int *comp, int req_comp) +{ + if (stbi__gif_test(s)) { + int layers = 0; + stbi_uc *u = 0; + stbi_uc *out = 0; + stbi_uc *two_back = 0; + stbi__gif g; + int stride; + memset(&g, 0, sizeof(g)); + if (delays) { + *delays = 0; + } + + do { + u = stbi__gif_load_next(s, &g, comp, req_comp, two_back); + if (u == (stbi_uc *) s) u = 0; // end of animated gif marker + + if (u) { + *x = g.w; + *y = g.h; + ++layers; + stride = g.w * g.h * 4; + + if (out) { + void *tmp = (stbi_uc*) STBI_REALLOC( out, layers * stride ); + if (NULL == tmp) { + STBI_FREE(g.out); + STBI_FREE(g.history); + STBI_FREE(g.background); + return stbi__errpuc("outofmem", "Out of memory"); + } + else + out = (stbi_uc*) tmp; + if (delays) { + *delays = (int*) STBI_REALLOC( *delays, sizeof(int) * layers ); + } + } else { + out = (stbi_uc*)stbi__malloc( layers * stride ); + if (delays) { + *delays = (int*) stbi__malloc( layers * sizeof(int) ); + } + } + memcpy( out + ((layers - 1) * stride), u, stride ); + if (layers >= 2) { + two_back = out - 2 * stride; + } + + if (delays) { + (*delays)[layers - 1U] = g.delay; + } + } + } while (u != 0); + + // free temp buffer; + STBI_FREE(g.out); + STBI_FREE(g.history); + STBI_FREE(g.background); + + // do the final conversion after loading everything; + if (req_comp && req_comp != 4) + out = stbi__convert_format(out, 4, req_comp, layers * g.w, g.h); + + *z = layers; + return out; + } else { + return stbi__errpuc("not GIF", "Image was not as a gif type."); + } +} + +static void *stbi__gif_load(stbi__context *s, int *x, int *y, int *comp, int req_comp, stbi__result_info *ri) +{ + stbi_uc *u = 0; + stbi__gif g; + memset(&g, 0, sizeof(g)); + STBI_NOTUSED(ri); + + u = stbi__gif_load_next(s, &g, comp, req_comp, 0); + if (u == (stbi_uc *) s) u = 0; // end of animated gif marker + if (u) { + *x = g.w; + *y = g.h; + + // moved conversion to after successful load so that the same + // can be done for multiple frames. + if (req_comp && req_comp != 4) + u = stbi__convert_format(u, 4, req_comp, g.w, g.h); + } else if (g.out) { + // if there was an error and we allocated an image buffer, free it! + STBI_FREE(g.out); + } + + // free buffers needed for multiple frame loading; + STBI_FREE(g.history); + STBI_FREE(g.background); + + return u; +} + +static int stbi__gif_info(stbi__context *s, int *x, int *y, int *comp) +{ + return stbi__gif_info_raw(s,x,y,comp); +} +#endif + +// ************************************************************************************************* +// Radiance RGBE HDR loader +// originally by Nicolas Schulz +#ifndef STBI_NO_HDR +static int stbi__hdr_test_core(stbi__context *s, const char *signature) +{ + int i; + for (i=0; signature[i]; ++i) + if (stbi__get8(s) != signature[i]) + return 0; + stbi__rewind(s); + return 1; +} + +static int stbi__hdr_test(stbi__context* s) +{ + int r = stbi__hdr_test_core(s, "#?RADIANCE\n"); + stbi__rewind(s); + if(!r) { + r = stbi__hdr_test_core(s, "#?RGBE\n"); + stbi__rewind(s); + } + return r; +} + +#define STBI__HDR_BUFLEN 1024 +static char *stbi__hdr_gettoken(stbi__context *z, char *buffer) +{ + int len=0; + char c = '\0'; + + c = (char) stbi__get8(z); + + while (!stbi__at_eof(z) && c != '\n') { + buffer[len++] = c; + if (len == STBI__HDR_BUFLEN-1) { + // flush to end of line + while (!stbi__at_eof(z) && stbi__get8(z) != '\n') + ; + break; + } + c = (char) stbi__get8(z); + } + + buffer[len] = 0; + return buffer; +} + +static void stbi__hdr_convert(float *output, stbi_uc *input, int req_comp) +{ + if ( input[3] != 0 ) { + float f1; + // Exponent + f1 = (float) ldexp(1.0f, input[3] - (int)(128 + 8)); + if (req_comp <= 2) + output[0] = (input[0] + input[1] + input[2]) * f1 / 3; + else { + output[0] = input[0] * f1; + output[1] = input[1] * f1; + output[2] = input[2] * f1; + } + if (req_comp == 2) output[1] = 1; + if (req_comp == 4) output[3] = 1; + } else { + switch (req_comp) { + case 4: output[3] = 1; /* fallthrough */ + case 3: output[0] = output[1] = output[2] = 0; + break; + case 2: output[1] = 1; /* fallthrough */ + case 1: output[0] = 0; + break; + } + } +} + +static float *stbi__hdr_load(stbi__context *s, int *x, int *y, int *comp, int req_comp, stbi__result_info *ri) +{ + char buffer[STBI__HDR_BUFLEN]; + char *token; + int valid = 0; + int width, height; + stbi_uc *scanline; + float *hdr_data; + int len; + unsigned char count, value; + int i, j, k, c1,c2, z; + const char *headerToken; + STBI_NOTUSED(ri); + + // Check identifier + headerToken = stbi__hdr_gettoken(s,buffer); + if (strcmp(headerToken, "#?RADIANCE") != 0 && strcmp(headerToken, "#?RGBE") != 0) + return stbi__errpf("not HDR", "Corrupt HDR image"); + + // Parse header + for(;;) { + token = stbi__hdr_gettoken(s,buffer); + if (token[0] == 0) break; + if (strcmp(token, "FORMAT=32-bit_rle_rgbe") == 0) valid = 1; + } + + if (!valid) return stbi__errpf("unsupported format", "Unsupported HDR format"); + + // Parse width and height + // can't use sscanf() if we're not using stdio! + token = stbi__hdr_gettoken(s,buffer); + if (strncmp(token, "-Y ", 3)) return stbi__errpf("unsupported data layout", "Unsupported HDR format"); + token += 3; + height = (int) strtol(token, &token, 10); + while (*token == ' ') ++token; + if (strncmp(token, "+X ", 3)) return stbi__errpf("unsupported data layout", "Unsupported HDR format"); + token += 3; + width = (int) strtol(token, NULL, 10); + + *x = width; + *y = height; + + if (comp) *comp = 3; + if (req_comp == 0) req_comp = 3; + + if (!stbi__mad4sizes_valid(width, height, req_comp, sizeof(float), 0)) + return stbi__errpf("too large", "HDR image is too large"); + + // Read data + hdr_data = (float *) stbi__malloc_mad4(width, height, req_comp, sizeof(float), 0); + if (!hdr_data) + return stbi__errpf("outofmem", "Out of memory"); + + // Load image data + // image data is stored as some number of sca + if ( width < 8 || width >= 32768) { + // Read flat data + for (j=0; j < height; ++j) { + for (i=0; i < width; ++i) { + stbi_uc rgbe[4]; + main_decode_loop: + stbi__getn(s, rgbe, 4); + stbi__hdr_convert(hdr_data + j * width * req_comp + i * req_comp, rgbe, req_comp); + } + } + } else { + // Read RLE-encoded data + scanline = NULL; + + for (j = 0; j < height; ++j) { + c1 = stbi__get8(s); + c2 = stbi__get8(s); + len = stbi__get8(s); + if (c1 != 2 || c2 != 2 || (len & 0x80)) { + // not run-length encoded, so we have to actually use THIS data as a decoded + // pixel (note this can't be a valid pixel--one of RGB must be >= 128) + stbi_uc rgbe[4]; + rgbe[0] = (stbi_uc) c1; + rgbe[1] = (stbi_uc) c2; + rgbe[2] = (stbi_uc) len; + rgbe[3] = (stbi_uc) stbi__get8(s); + stbi__hdr_convert(hdr_data, rgbe, req_comp); + i = 1; + j = 0; + STBI_FREE(scanline); + goto main_decode_loop; // yes, this makes no sense + } + len <<= 8; + len |= stbi__get8(s); + if (len != width) { STBI_FREE(hdr_data); STBI_FREE(scanline); return stbi__errpf("invalid decoded scanline length", "corrupt HDR"); } + if (scanline == NULL) { + scanline = (stbi_uc *) stbi__malloc_mad2(width, 4, 0); + if (!scanline) { + STBI_FREE(hdr_data); + return stbi__errpf("outofmem", "Out of memory"); + } + } + + for (k = 0; k < 4; ++k) { + int nleft; + i = 0; + while ((nleft = width - i) > 0) { + count = stbi__get8(s); + if (count > 128) { + // Run + value = stbi__get8(s); + count -= 128; + if (count > nleft) { STBI_FREE(hdr_data); STBI_FREE(scanline); return stbi__errpf("corrupt", "bad RLE data in HDR"); } + for (z = 0; z < count; ++z) + scanline[i++ * 4 + k] = value; + } else { + // Dump + if (count > nleft) { STBI_FREE(hdr_data); STBI_FREE(scanline); return stbi__errpf("corrupt", "bad RLE data in HDR"); } + for (z = 0; z < count; ++z) + scanline[i++ * 4 + k] = stbi__get8(s); + } + } + } + for (i=0; i < width; ++i) + stbi__hdr_convert(hdr_data+(j*width + i)*req_comp, scanline + i*4, req_comp); + } + if (scanline) + STBI_FREE(scanline); + } + + return hdr_data; +} + +static int stbi__hdr_info(stbi__context *s, int *x, int *y, int *comp) +{ + char buffer[STBI__HDR_BUFLEN]; + char *token; + int valid = 0; + int dummy; + + if (!x) x = &dummy; + if (!y) y = &dummy; + if (!comp) comp = &dummy; + + if (stbi__hdr_test(s) == 0) { + stbi__rewind( s ); + return 0; + } + + for(;;) { + token = stbi__hdr_gettoken(s,buffer); + if (token[0] == 0) break; + if (strcmp(token, "FORMAT=32-bit_rle_rgbe") == 0) valid = 1; + } + + if (!valid) { + stbi__rewind( s ); + return 0; + } + token = stbi__hdr_gettoken(s,buffer); + if (strncmp(token, "-Y ", 3)) { + stbi__rewind( s ); + return 0; + } + token += 3; + *y = (int) strtol(token, &token, 10); + while (*token == ' ') ++token; + if (strncmp(token, "+X ", 3)) { + stbi__rewind( s ); + return 0; + } + token += 3; + *x = (int) strtol(token, NULL, 10); + *comp = 3; + return 1; +} +#endif // STBI_NO_HDR + +#ifndef STBI_NO_BMP +static int stbi__bmp_info(stbi__context *s, int *x, int *y, int *comp) +{ + void *p; + stbi__bmp_data info; + + info.all_a = 255; + p = stbi__bmp_parse_header(s, &info); + stbi__rewind( s ); + if (p == NULL) + return 0; + if (x) *x = s->img_x; + if (y) *y = s->img_y; + if (comp) { + if (info.bpp == 24 && info.ma == 0xff000000) + *comp = 3; + else + *comp = info.ma ? 4 : 3; + } + return 1; +} +#endif + +#ifndef STBI_NO_PSD +static int stbi__psd_info(stbi__context *s, int *x, int *y, int *comp) +{ + int channelCount, dummy, depth; + if (!x) x = &dummy; + if (!y) y = &dummy; + if (!comp) comp = &dummy; + if (stbi__get32be(s) != 0x38425053) { + stbi__rewind( s ); + return 0; + } + if (stbi__get16be(s) != 1) { + stbi__rewind( s ); + return 0; + } + stbi__skip(s, 6); + channelCount = stbi__get16be(s); + if (channelCount < 0 || channelCount > 16) { + stbi__rewind( s ); + return 0; + } + *y = stbi__get32be(s); + *x = stbi__get32be(s); + depth = stbi__get16be(s); + if (depth != 8 && depth != 16) { + stbi__rewind( s ); + return 0; + } + if (stbi__get16be(s) != 3) { + stbi__rewind( s ); + return 0; + } + *comp = 4; + return 1; +} + +static int stbi__psd_is16(stbi__context *s) +{ + int channelCount, depth; + if (stbi__get32be(s) != 0x38425053) { + stbi__rewind( s ); + return 0; + } + if (stbi__get16be(s) != 1) { + stbi__rewind( s ); + return 0; + } + stbi__skip(s, 6); + channelCount = stbi__get16be(s); + if (channelCount < 0 || channelCount > 16) { + stbi__rewind( s ); + return 0; + } + (void) stbi__get32be(s); + (void) stbi__get32be(s); + depth = stbi__get16be(s); + if (depth != 16) { + stbi__rewind( s ); + return 0; + } + return 1; +} +#endif + +#ifndef STBI_NO_PIC +static int stbi__pic_info(stbi__context *s, int *x, int *y, int *comp) +{ + int act_comp=0,num_packets=0,chained,dummy; + stbi__pic_packet packets[10]; + + if (!x) x = &dummy; + if (!y) y = &dummy; + if (!comp) comp = &dummy; + + if (!stbi__pic_is4(s,"\x53\x80\xF6\x34")) { + stbi__rewind(s); + return 0; + } + + stbi__skip(s, 88); + + *x = stbi__get16be(s); + *y = stbi__get16be(s); + if (stbi__at_eof(s)) { + stbi__rewind( s); + return 0; + } + if ( (*x) != 0 && (1 << 28) / (*x) < (*y)) { + stbi__rewind( s ); + return 0; + } + + stbi__skip(s, 8); + + do { + stbi__pic_packet *packet; + + if (num_packets==sizeof(packets)/sizeof(packets[0])) + return 0; + + packet = &packets[num_packets++]; + chained = stbi__get8(s); + packet->size = stbi__get8(s); + packet->type = stbi__get8(s); + packet->channel = stbi__get8(s); + act_comp |= packet->channel; + + if (stbi__at_eof(s)) { + stbi__rewind( s ); + return 0; + } + if (packet->size != 8) { + stbi__rewind( s ); + return 0; + } + } while (chained); + + *comp = (act_comp & 0x10 ? 4 : 3); + + return 1; +} +#endif + +// ************************************************************************************************* +// Portable Gray Map and Portable Pixel Map loader +// by Ken Miller +// +// PGM: http://netpbm.sourceforge.net/doc/pgm.html +// PPM: http://netpbm.sourceforge.net/doc/ppm.html +// +// Known limitations: +// Does not support comments in the header section +// Does not support ASCII image data (formats P2 and P3) +// Does not support 16-bit-per-channel + +#ifndef STBI_NO_PNM + +static int stbi__pnm_test(stbi__context *s) +{ + char p, t; + p = (char) stbi__get8(s); + t = (char) stbi__get8(s); + if (p != 'P' || (t != '5' && t != '6')) { + stbi__rewind( s ); + return 0; + } + return 1; +} + +static void *stbi__pnm_load(stbi__context *s, int *x, int *y, int *comp, int req_comp, stbi__result_info *ri) +{ + stbi_uc *out; + STBI_NOTUSED(ri); + + if (!stbi__pnm_info(s, (int *)&s->img_x, (int *)&s->img_y, (int *)&s->img_n)) + return 0; + + *x = s->img_x; + *y = s->img_y; + if (comp) *comp = s->img_n; + + if (!stbi__mad3sizes_valid(s->img_n, s->img_x, s->img_y, 0)) + return stbi__errpuc("too large", "PNM too large"); + + out = (stbi_uc *) stbi__malloc_mad3(s->img_n, s->img_x, s->img_y, 0); + if (!out) return stbi__errpuc("outofmem", "Out of memory"); + stbi__getn(s, out, s->img_n * s->img_x * s->img_y); + + if (req_comp && req_comp != s->img_n) { + out = stbi__convert_format(out, s->img_n, req_comp, s->img_x, s->img_y); + if (out == NULL) return out; // stbi__convert_format frees input on failure + } + return out; +} + +static int stbi__pnm_isspace(char c) +{ + return c == ' ' || c == '\t' || c == '\n' || c == '\v' || c == '\f' || c == '\r'; +} + +static void stbi__pnm_skip_whitespace(stbi__context *s, char *c) +{ + for (;;) { + while (!stbi__at_eof(s) && stbi__pnm_isspace(*c)) + *c = (char) stbi__get8(s); + + if (stbi__at_eof(s) || *c != '#') + break; + + while (!stbi__at_eof(s) && *c != '\n' && *c != '\r' ) + *c = (char) stbi__get8(s); + } +} + +static int stbi__pnm_isdigit(char c) +{ + return c >= '0' && c <= '9'; +} + +static int stbi__pnm_getinteger(stbi__context *s, char *c) +{ + int value = 0; + + while (!stbi__at_eof(s) && stbi__pnm_isdigit(*c)) { + value = value*10 + (*c - '0'); + *c = (char) stbi__get8(s); + } + + return value; +} + +static int stbi__pnm_info(stbi__context *s, int *x, int *y, int *comp) +{ + int maxv, dummy; + char c, p, t; + + if (!x) x = &dummy; + if (!y) y = &dummy; + if (!comp) comp = &dummy; + + stbi__rewind(s); + + // Get identifier + p = (char) stbi__get8(s); + t = (char) stbi__get8(s); + if (p != 'P' || (t != '5' && t != '6')) { + stbi__rewind(s); + return 0; + } + + *comp = (t == '6') ? 3 : 1; // '5' is 1-component .pgm; '6' is 3-component .ppm + + c = (char) stbi__get8(s); + stbi__pnm_skip_whitespace(s, &c); + + *x = stbi__pnm_getinteger(s, &c); // read width + stbi__pnm_skip_whitespace(s, &c); + + *y = stbi__pnm_getinteger(s, &c); // read height + stbi__pnm_skip_whitespace(s, &c); + + maxv = stbi__pnm_getinteger(s, &c); // read max value + + if (maxv > 255) + return stbi__err("max value > 255", "PPM image not 8-bit"); + else + return 1; +} +#endif + +static int stbi__info_main(stbi__context *s, int *x, int *y, int *comp) +{ + #ifndef STBI_NO_JPEG + if (stbi__jpeg_info(s, x, y, comp)) return 1; + #endif + + #ifndef STBI_NO_PNG + if (stbi__png_info(s, x, y, comp)) return 1; + #endif + + #ifndef STBI_NO_GIF + if (stbi__gif_info(s, x, y, comp)) return 1; + #endif + + #ifndef STBI_NO_BMP + if (stbi__bmp_info(s, x, y, comp)) return 1; + #endif + + #ifndef STBI_NO_PSD + if (stbi__psd_info(s, x, y, comp)) return 1; + #endif + + #ifndef STBI_NO_PIC + if (stbi__pic_info(s, x, y, comp)) return 1; + #endif + + #ifndef STBI_NO_PNM + if (stbi__pnm_info(s, x, y, comp)) return 1; + #endif + + #ifndef STBI_NO_HDR + if (stbi__hdr_info(s, x, y, comp)) return 1; + #endif + + // test tga last because it's a crappy test! + #ifndef STBI_NO_TGA + if (stbi__tga_info(s, x, y, comp)) + return 1; + #endif + return stbi__err("unknown image type", "Image not of any known type, or corrupt"); +} + +static int stbi__is_16_main(stbi__context *s) +{ + #ifndef STBI_NO_PNG + if (stbi__png_is16(s)) return 1; + #endif + + #ifndef STBI_NO_PSD + if (stbi__psd_is16(s)) return 1; + #endif + + return 0; +} + +#ifndef STBI_NO_STDIO +STBIDEF int stbi_info(char const *filename, int *x, int *y, int *comp) +{ + FILE *f = stbi__fopen(filename, "rb"); + int result; + if (!f) return stbi__err("can't fopen", "Unable to open file"); + result = stbi_info_from_file(f, x, y, comp); + fclose(f); + return result; +} + +STBIDEF int stbi_info_from_file(FILE *f, int *x, int *y, int *comp) +{ + int r; + stbi__context s; + long pos = ftell(f); + stbi__start_file(&s, f); + r = stbi__info_main(&s,x,y,comp); + fseek(f,pos,SEEK_SET); + return r; +} + +STBIDEF int stbi_is_16_bit(char const *filename) +{ + FILE *f = stbi__fopen(filename, "rb"); + int result; + if (!f) return stbi__err("can't fopen", "Unable to open file"); + result = stbi_is_16_bit_from_file(f); + fclose(f); + return result; +} + +STBIDEF int stbi_is_16_bit_from_file(FILE *f) +{ + int r; + stbi__context s; + long pos = ftell(f); + stbi__start_file(&s, f); + r = stbi__is_16_main(&s); + fseek(f,pos,SEEK_SET); + return r; +} +#endif // !STBI_NO_STDIO + +STBIDEF int stbi_info_from_memory(stbi_uc const *buffer, int len, int *x, int *y, int *comp) +{ + stbi__context s; + stbi__start_mem(&s,buffer,len); + return stbi__info_main(&s,x,y,comp); +} + +STBIDEF int stbi_info_from_callbacks(stbi_io_callbacks const *c, void *user, int *x, int *y, int *comp) +{ + stbi__context s; + stbi__start_callbacks(&s, (stbi_io_callbacks *) c, user); + return stbi__info_main(&s,x,y,comp); +} + +STBIDEF int stbi_is_16_bit_from_memory(stbi_uc const *buffer, int len) +{ + stbi__context s; + stbi__start_mem(&s,buffer,len); + return stbi__is_16_main(&s); +} + +STBIDEF int stbi_is_16_bit_from_callbacks(stbi_io_callbacks const *c, void *user) +{ + stbi__context s; + stbi__start_callbacks(&s, (stbi_io_callbacks *) c, user); + return stbi__is_16_main(&s); +} + +#endif // STB_IMAGE_IMPLEMENTATION + +/* + revision history: + 2.20 (2019-02-07) support utf8 filenames in Windows; fix warnings and platform ifdefs + 2.19 (2018-02-11) fix warning + 2.18 (2018-01-30) fix warnings + 2.17 (2018-01-29) change sbti__shiftsigned to avoid clang -O2 bug + 1-bit BMP + *_is_16_bit api + avoid warnings + 2.16 (2017-07-23) all functions have 16-bit variants; + STBI_NO_STDIO works again; + compilation fixes; + fix rounding in unpremultiply; + optimize vertical flip; + disable raw_len validation; + documentation fixes + 2.15 (2017-03-18) fix png-1,2,4 bug; now all Imagenet JPGs decode; + warning fixes; disable run-time SSE detection on gcc; + uniform handling of optional "return" values; + thread-safe initialization of zlib tables + 2.14 (2017-03-03) remove deprecated STBI_JPEG_OLD; fixes for Imagenet JPGs + 2.13 (2016-11-29) add 16-bit API, only supported for PNG right now + 2.12 (2016-04-02) fix typo in 2.11 PSD fix that caused crashes + 2.11 (2016-04-02) allocate large structures on the stack + remove white matting for transparent PSD + fix reported channel count for PNG & BMP + re-enable SSE2 in non-gcc 64-bit + support RGB-formatted JPEG + read 16-bit PNGs (only as 8-bit) + 2.10 (2016-01-22) avoid warning introduced in 2.09 by STBI_REALLOC_SIZED + 2.09 (2016-01-16) allow comments in PNM files + 16-bit-per-pixel TGA (not bit-per-component) + info() for TGA could break due to .hdr handling + info() for BMP to shares code instead of sloppy parse + can use STBI_REALLOC_SIZED if allocator doesn't support realloc + code cleanup + 2.08 (2015-09-13) fix to 2.07 cleanup, reading RGB PSD as RGBA + 2.07 (2015-09-13) fix compiler warnings + partial animated GIF support + limited 16-bpc PSD support + #ifdef unused functions + bug with < 92 byte PIC,PNM,HDR,TGA + 2.06 (2015-04-19) fix bug where PSD returns wrong '*comp' value + 2.05 (2015-04-19) fix bug in progressive JPEG handling, fix warning + 2.04 (2015-04-15) try to re-enable SIMD on MinGW 64-bit + 2.03 (2015-04-12) extra corruption checking (mmozeiko) + stbi_set_flip_vertically_on_load (nguillemot) + fix NEON support; fix mingw support + 2.02 (2015-01-19) fix incorrect assert, fix warning + 2.01 (2015-01-17) fix various warnings; suppress SIMD on gcc 32-bit without -msse2 + 2.00b (2014-12-25) fix STBI_MALLOC in progressive JPEG + 2.00 (2014-12-25) optimize JPG, including x86 SSE2 & NEON SIMD (ryg) + progressive JPEG (stb) + PGM/PPM support (Ken Miller) + STBI_MALLOC,STBI_REALLOC,STBI_FREE + GIF bugfix -- seemingly never worked + STBI_NO_*, STBI_ONLY_* + 1.48 (2014-12-14) fix incorrectly-named assert() + 1.47 (2014-12-14) 1/2/4-bit PNG support, both direct and paletted (Omar Cornut & stb) + optimize PNG (ryg) + fix bug in interlaced PNG with user-specified channel count (stb) + 1.46 (2014-08-26) + fix broken tRNS chunk (colorkey-style transparency) in non-paletted PNG + 1.45 (2014-08-16) + fix MSVC-ARM internal compiler error by wrapping malloc + 1.44 (2014-08-07) + various warning fixes from Ronny Chevalier + 1.43 (2014-07-15) + fix MSVC-only compiler problem in code changed in 1.42 + 1.42 (2014-07-09) + don't define _CRT_SECURE_NO_WARNINGS (affects user code) + fixes to stbi__cleanup_jpeg path + added STBI_ASSERT to avoid requiring assert.h + 1.41 (2014-06-25) + fix search&replace from 1.36 that messed up comments/error messages + 1.40 (2014-06-22) + fix gcc struct-initialization warning + 1.39 (2014-06-15) + fix to TGA optimization when req_comp != number of components in TGA; + fix to GIF loading because BMP wasn't rewinding (whoops, no GIFs in my test suite) + add support for BMP version 5 (more ignored fields) + 1.38 (2014-06-06) + suppress MSVC warnings on integer casts truncating values + fix accidental rename of 'skip' field of I/O + 1.37 (2014-06-04) + remove duplicate typedef + 1.36 (2014-06-03) + convert to header file single-file library + if de-iphone isn't set, load iphone images color-swapped instead of returning NULL + 1.35 (2014-05-27) + various warnings + fix broken STBI_SIMD path + fix bug where stbi_load_from_file no longer left file pointer in correct place + fix broken non-easy path for 32-bit BMP (possibly never used) + TGA optimization by Arseny Kapoulkine + 1.34 (unknown) + use STBI_NOTUSED in stbi__resample_row_generic(), fix one more leak in tga failure case + 1.33 (2011-07-14) + make stbi_is_hdr work in STBI_NO_HDR (as specified), minor compiler-friendly improvements + 1.32 (2011-07-13) + support for "info" function for all supported filetypes (SpartanJ) + 1.31 (2011-06-20) + a few more leak fixes, bug in PNG handling (SpartanJ) + 1.30 (2011-06-11) + added ability to load files via callbacks to accomidate custom input streams (Ben Wenger) + removed deprecated format-specific test/load functions + removed support for installable file formats (stbi_loader) -- would have been broken for IO callbacks anyway + error cases in bmp and tga give messages and don't leak (Raymond Barbiero, grisha) + fix inefficiency in decoding 32-bit BMP (David Woo) + 1.29 (2010-08-16) + various warning fixes from Aurelien Pocheville + 1.28 (2010-08-01) + fix bug in GIF palette transparency (SpartanJ) + 1.27 (2010-08-01) + cast-to-stbi_uc to fix warnings + 1.26 (2010-07-24) + fix bug in file buffering for PNG reported by SpartanJ + 1.25 (2010-07-17) + refix trans_data warning (Won Chun) + 1.24 (2010-07-12) + perf improvements reading from files on platforms with lock-heavy fgetc() + minor perf improvements for jpeg + deprecated type-specific functions so we'll get feedback if they're needed + attempt to fix trans_data warning (Won Chun) + 1.23 fixed bug in iPhone support + 1.22 (2010-07-10) + removed image *writing* support + stbi_info support from Jetro Lauha + GIF support from Jean-Marc Lienher + iPhone PNG-extensions from James Brown + warning-fixes from Nicolas Schulz and Janez Zemva (i.stbi__err. Janez (U+017D)emva) + 1.21 fix use of 'stbi_uc' in header (reported by jon blow) + 1.20 added support for Softimage PIC, by Tom Seddon + 1.19 bug in interlaced PNG corruption check (found by ryg) + 1.18 (2008-08-02) + fix a threading bug (local mutable static) + 1.17 support interlaced PNG + 1.16 major bugfix - stbi__convert_format converted one too many pixels + 1.15 initialize some fields for thread safety + 1.14 fix threadsafe conversion bug + header-file-only version (#define STBI_HEADER_FILE_ONLY before including) + 1.13 threadsafe + 1.12 const qualifiers in the API + 1.11 Support installable IDCT, colorspace conversion routines + 1.10 Fixes for 64-bit (don't use "unsigned long") + optimized upsampling by Fabian "ryg" Giesen + 1.09 Fix format-conversion for PSD code (bad global variables!) + 1.08 Thatcher Ulrich's PSD code integrated by Nicolas Schulz + 1.07 attempt to fix C++ warning/errors again + 1.06 attempt to fix C++ warning/errors again + 1.05 fix TGA loading to return correct *comp and use good luminance calc + 1.04 default float alpha is 1, not 255; use 'void *' for stbi_image_free + 1.03 bugfixes to STBI_NO_STDIO, STBI_NO_HDR + 1.02 support for (subset of) HDR files, float interface for preferred access to them + 1.01 fix bug: possible bug in handling right-side up bmps... not sure + fix bug: the stbi__bmp_load() and stbi__tga_load() functions didn't work at all + 1.00 interface to zlib that skips zlib header + 0.99 correct handling of alpha in palette + 0.98 TGA loader by lonesock; dynamically add loaders (untested) + 0.97 jpeg errors on too large a file; also catch another malloc failure + 0.96 fix detection of invalid v value - particleman@mollyrocket forum + 0.95 during header scan, seek to markers in case of padding + 0.94 STBI_NO_STDIO to disable stdio usage; rename all #defines the same + 0.93 handle jpegtran output; verbose errors + 0.92 read 4,8,16,24,32-bit BMP files of several formats + 0.91 output 24-bit Windows 3.0 BMP files + 0.90 fix a few more warnings; bump version number to approach 1.0 + 0.61 bugfixes due to Marc LeBlanc, Christopher Lloyd + 0.60 fix compiling as c++ + 0.59 fix warnings: merge Dave Moore's -Wall fixes + 0.58 fix bug: zlib uncompressed mode len/nlen was wrong endian + 0.57 fix bug: jpg last huffman symbol before marker was >9 bits but less than 16 available + 0.56 fix bug: zlib uncompressed mode len vs. nlen + 0.55 fix bug: restart_interval not initialized to 0 + 0.54 allow NULL for 'int *comp' + 0.53 fix bug in png 3->4; speedup png decoding + 0.52 png handles req_comp=3,4 directly; minor cleanup; jpeg comments + 0.51 obey req_comp requests, 1-component jpegs return as 1-component, + on 'test' only check type, not whether we support this variant + 0.50 (2006-11-19) + first released version +*/ + + +/* +------------------------------------------------------------------------------ +This software is available under 2 licenses -- choose whichever you prefer. +------------------------------------------------------------------------------ +ALTERNATIVE A - MIT License +Copyright (c) 2017 Sean Barrett +Permission is hereby granted, free of charge, to any person obtaining a copy of +this software and associated documentation files (the "Software"), to deal in +the Software without restriction, including without limitation the rights to +use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies +of the Software, and to permit persons to whom the Software is furnished to do +so, subject to the following conditions: +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +SOFTWARE. +------------------------------------------------------------------------------ +ALTERNATIVE B - Public Domain (www.unlicense.org) +This is free and unencumbered software released into the public domain. +Anyone is free to copy, modify, publish, use, compile, sell, or distribute this +software, either in source code form or as a compiled binary, for any purpose, +commercial or non-commercial, and by any means. +In jurisdictions that recognize copyright laws, the author or authors of this +software dedicate any and all copyright interest in the software to the public +domain. We make this dedication for the benefit of the public at large and to +the detriment of our heirs and successors. We intend this dedication to be an +overt act of relinquishment in perpetuity of all present and future rights to +this software under copyright law. +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN +ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION +WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. +------------------------------------------------------------------------------ +*/ diff --git a/libs/stb/stb_image_write.h b/libs/stb/stb_image_write.h new file mode 100644 index 0000000000..cffd473c1f --- /dev/null +++ b/libs/stb/stb_image_write.h @@ -0,0 +1,1666 @@ +/* stb_image_write - v1.14 - public domain - http://nothings.org/stb + writes out PNG/BMP/TGA/JPEG/HDR images to C stdio - Sean Barrett 2010-2015 + no warranty implied; use at your own risk + + Before #including, + + #define STB_IMAGE_WRITE_IMPLEMENTATION + + in the file that you want to have the implementation. + + Will probably not work correctly with strict-aliasing optimizations. + +ABOUT: + + This header file is a library for writing images to C stdio or a callback. + + The PNG output is not optimal; it is 20-50% larger than the file + written by a decent optimizing implementation; though providing a custom + zlib compress function (see STBIW_ZLIB_COMPRESS) can mitigate that. + This library is designed for source code compactness and simplicity, + not optimal image file size or run-time performance. + +BUILDING: + + You can #define STBIW_ASSERT(x) before the #include to avoid using assert.h. + You can #define STBIW_MALLOC(), STBIW_REALLOC(), and STBIW_FREE() to replace + malloc,realloc,free. + You can #define STBIW_MEMMOVE() to replace memmove() + You can #define STBIW_ZLIB_COMPRESS to use a custom zlib-style compress function + for PNG compression (instead of the builtin one), it must have the following signature: + unsigned char * my_compress(unsigned char *data, int data_len, int *out_len, int quality); + The returned data will be freed with STBIW_FREE() (free() by default), + so it must be heap allocated with STBIW_MALLOC() (malloc() by default), + +UNICODE: + + If compiling for Windows and you wish to use Unicode filenames, compile + with + #define STBIW_WINDOWS_UTF8 + and pass utf8-encoded filenames. Call stbiw_convert_wchar_to_utf8 to convert + Windows wchar_t filenames to utf8. + +USAGE: + + There are five functions, one for each image file format: + + int stbi_write_png(char const *filename, int w, int h, int comp, const void *data, int stride_in_bytes); + int stbi_write_bmp(char const *filename, int w, int h, int comp, const void *data); + int stbi_write_tga(char const *filename, int w, int h, int comp, const void *data); + int stbi_write_jpg(char const *filename, int w, int h, int comp, const void *data, int quality); + int stbi_write_hdr(char const *filename, int w, int h, int comp, const float *data); + + void stbi_flip_vertically_on_write(int flag); // flag is non-zero to flip data vertically + + There are also five equivalent functions that use an arbitrary write function. You are + expected to open/close your file-equivalent before and after calling these: + + int stbi_write_png_to_func(stbi_write_func *func, void *context, int w, int h, int comp, const void *data, int stride_in_bytes); + int stbi_write_bmp_to_func(stbi_write_func *func, void *context, int w, int h, int comp, const void *data); + int stbi_write_tga_to_func(stbi_write_func *func, void *context, int w, int h, int comp, const void *data); + int stbi_write_hdr_to_func(stbi_write_func *func, void *context, int w, int h, int comp, const float *data); + int stbi_write_jpg_to_func(stbi_write_func *func, void *context, int x, int y, int comp, const void *data, int quality); + + where the callback is: + void stbi_write_func(void *context, void *data, int size); + + You can configure it with these global variables: + int stbi_write_tga_with_rle; // defaults to true; set to 0 to disable RLE + int stbi_write_png_compression_level; // defaults to 8; set to higher for more compression + int stbi_write_force_png_filter; // defaults to -1; set to 0..5 to force a filter mode + + + You can define STBI_WRITE_NO_STDIO to disable the file variant of these + functions, so the library will not use stdio.h at all. However, this will + also disable HDR writing, because it requires stdio for formatted output. + + Each function returns 0 on failure and non-0 on success. + + The functions create an image file defined by the parameters. The image + is a rectangle of pixels stored from left-to-right, top-to-bottom. + Each pixel contains 'comp' channels of data stored interleaved with 8-bits + per channel, in the following order: 1=Y, 2=YA, 3=RGB, 4=RGBA. (Y is + monochrome color.) The rectangle is 'w' pixels wide and 'h' pixels tall. + The *data pointer points to the first byte of the top-left-most pixel. + For PNG, "stride_in_bytes" is the distance in bytes from the first byte of + a row of pixels to the first byte of the next row of pixels. + + PNG creates output files with the same number of components as the input. + The BMP format expands Y to RGB in the file format and does not + output alpha. + + PNG supports writing rectangles of data even when the bytes storing rows of + data are not consecutive in memory (e.g. sub-rectangles of a larger image), + by supplying the stride between the beginning of adjacent rows. The other + formats do not. (Thus you cannot write a native-format BMP through the BMP + writer, both because it is in BGR order and because it may have padding + at the end of the line.) + + PNG allows you to set the deflate compression level by setting the global + variable 'stbi_write_png_compression_level' (it defaults to 8). + + HDR expects linear float data. Since the format is always 32-bit rgb(e) + data, alpha (if provided) is discarded, and for monochrome data it is + replicated across all three channels. + + TGA supports RLE or non-RLE compressed data. To use non-RLE-compressed + data, set the global variable 'stbi_write_tga_with_rle' to 0. + + JPEG does ignore alpha channels in input data; quality is between 1 and 100. + Higher quality looks better but results in a bigger image. + JPEG baseline (no JPEG progressive). + +CREDITS: + + + Sean Barrett - PNG/BMP/TGA + Baldur Karlsson - HDR + Jean-Sebastien Guay - TGA monochrome + Tim Kelsey - misc enhancements + Alan Hickman - TGA RLE + Emmanuel Julien - initial file IO callback implementation + Jon Olick - original jo_jpeg.cpp code + Daniel Gibson - integrate JPEG, allow external zlib + Aarni Koskela - allow choosing PNG filter + + bugfixes: + github:Chribba + Guillaume Chereau + github:jry2 + github:romigrou + Sergio Gonzalez + Jonas Karlsson + Filip Wasil + Thatcher Ulrich + github:poppolopoppo + Patrick Boettcher + github:xeekworx + Cap Petschulat + Simon Rodriguez + Ivan Tikhonov + github:ignotion + Adam Schackart + +LICENSE + + See end of file for license information. + +*/ + +#ifndef INCLUDE_STB_IMAGE_WRITE_H +#define INCLUDE_STB_IMAGE_WRITE_H + +#include + +// if STB_IMAGE_WRITE_STATIC causes problems, try defining STBIWDEF to 'inline' or 'static inline' +#ifndef STBIWDEF +#ifdef STB_IMAGE_WRITE_STATIC +#define STBIWDEF static +#else +#ifdef __cplusplus +#define STBIWDEF extern "C" +#else +#define STBIWDEF extern +#endif +#endif +#endif + +#ifndef STB_IMAGE_WRITE_STATIC // C++ forbids static forward declarations +extern int stbi_write_tga_with_rle; +extern int stbi_write_png_compression_level; +extern int stbi_write_force_png_filter; +#endif + +#ifndef STBI_WRITE_NO_STDIO +STBIWDEF int stbi_write_png(char const *filename, int w, int h, int comp, const void *data, int stride_in_bytes); +STBIWDEF int stbi_write_bmp(char const *filename, int w, int h, int comp, const void *data); +STBIWDEF int stbi_write_tga(char const *filename, int w, int h, int comp, const void *data); +STBIWDEF int stbi_write_hdr(char const *filename, int w, int h, int comp, const float *data); +STBIWDEF int stbi_write_jpg(char const *filename, int x, int y, int comp, const void *data, int quality); + +#ifdef STBI_WINDOWS_UTF8 +STBIWDEF int stbiw_convert_wchar_to_utf8(char *buffer, size_t bufferlen, const wchar_t* input); +#endif +#endif + +typedef void stbi_write_func(void *context, void *data, int size); + +STBIWDEF int stbi_write_png_to_func(stbi_write_func *func, void *context, int w, int h, int comp, const void *data, int stride_in_bytes); +STBIWDEF int stbi_write_bmp_to_func(stbi_write_func *func, void *context, int w, int h, int comp, const void *data); +STBIWDEF int stbi_write_tga_to_func(stbi_write_func *func, void *context, int w, int h, int comp, const void *data); +STBIWDEF int stbi_write_hdr_to_func(stbi_write_func *func, void *context, int w, int h, int comp, const float *data); +STBIWDEF int stbi_write_jpg_to_func(stbi_write_func *func, void *context, int x, int y, int comp, const void *data, int quality); + +STBIWDEF void stbi_flip_vertically_on_write(int flip_boolean); + +#endif//INCLUDE_STB_IMAGE_WRITE_H + +#ifdef STB_IMAGE_WRITE_IMPLEMENTATION + +#ifdef _WIN32 + #ifndef _CRT_SECURE_NO_WARNINGS + #define _CRT_SECURE_NO_WARNINGS + #endif + #ifndef _CRT_NONSTDC_NO_DEPRECATE + #define _CRT_NONSTDC_NO_DEPRECATE + #endif +#endif + +#ifndef STBI_WRITE_NO_STDIO +#include +#endif // STBI_WRITE_NO_STDIO + +#include +#include +#include +#include + +#if defined(STBIW_MALLOC) && defined(STBIW_FREE) && (defined(STBIW_REALLOC) || defined(STBIW_REALLOC_SIZED)) +// ok +#elif !defined(STBIW_MALLOC) && !defined(STBIW_FREE) && !defined(STBIW_REALLOC) && !defined(STBIW_REALLOC_SIZED) +// ok +#else +#error "Must define all or none of STBIW_MALLOC, STBIW_FREE, and STBIW_REALLOC (or STBIW_REALLOC_SIZED)." +#endif + +#ifndef STBIW_MALLOC +#define STBIW_MALLOC(sz) malloc(sz) +#define STBIW_REALLOC(p,newsz) realloc(p,newsz) +#define STBIW_FREE(p) free(p) +#endif + +#ifndef STBIW_REALLOC_SIZED +#define STBIW_REALLOC_SIZED(p,oldsz,newsz) STBIW_REALLOC(p,newsz) +#endif + + +#ifndef STBIW_MEMMOVE +#define STBIW_MEMMOVE(a,b,sz) memmove(a,b,sz) +#endif + + +#ifndef STBIW_ASSERT +#include +#define STBIW_ASSERT(x) assert(x) +#endif + +#define STBIW_UCHAR(x) (unsigned char) ((x) & 0xff) + +#ifdef STB_IMAGE_WRITE_STATIC +static int stbi_write_png_compression_level = 8; +static int stbi_write_tga_with_rle = 1; +static int stbi_write_force_png_filter = -1; +#else +int stbi_write_png_compression_level = 8; +int stbi_write_tga_with_rle = 1; +int stbi_write_force_png_filter = -1; +#endif + +static int stbi__flip_vertically_on_write = 0; + +STBIWDEF void stbi_flip_vertically_on_write(int flag) +{ + stbi__flip_vertically_on_write = flag; +} + +typedef struct +{ + stbi_write_func *func; + void *context; +} stbi__write_context; + +// initialize a callback-based context +static void stbi__start_write_callbacks(stbi__write_context *s, stbi_write_func *c, void *context) +{ + s->func = c; + s->context = context; +} + +#ifndef STBI_WRITE_NO_STDIO + +static void stbi__stdio_write(void *context, void *data, int size) +{ + fwrite(data,1,size,(FILE*) context); +} + +#if defined(_MSC_VER) && defined(STBI_WINDOWS_UTF8) +#ifdef __cplusplus +#define STBIW_EXTERN extern "C" +#else +#define STBIW_EXTERN extern +#endif +STBIW_EXTERN __declspec(dllimport) int __stdcall MultiByteToWideChar(unsigned int cp, unsigned long flags, const char *str, int cbmb, wchar_t *widestr, int cchwide); +STBIW_EXTERN __declspec(dllimport) int __stdcall WideCharToMultiByte(unsigned int cp, unsigned long flags, const wchar_t *widestr, int cchwide, char *str, int cbmb, const char *defchar, int *used_default); + +STBIWDEF int stbiw_convert_wchar_to_utf8(char *buffer, size_t bufferlen, const wchar_t* input) +{ + return WideCharToMultiByte(65001 /* UTF8 */, 0, input, -1, buffer, (int) bufferlen, NULL, NULL); +} +#endif + +static FILE *stbiw__fopen(char const *filename, char const *mode) +{ + FILE *f; +#if defined(_MSC_VER) && defined(STBI_WINDOWS_UTF8) + wchar_t wMode[64]; + wchar_t wFilename[1024]; + if (0 == MultiByteToWideChar(65001 /* UTF8 */, 0, filename, -1, wFilename, sizeof(wFilename))) + return 0; + + if (0 == MultiByteToWideChar(65001 /* UTF8 */, 0, mode, -1, wMode, sizeof(wMode))) + return 0; + +#if _MSC_VER >= 1400 + if (0 != _wfopen_s(&f, wFilename, wMode)) + f = 0; +#else + f = _wfopen(wFilename, wMode); +#endif + +#elif defined(_MSC_VER) && _MSC_VER >= 1400 + if (0 != fopen_s(&f, filename, mode)) + f=0; +#else + f = fopen(filename, mode); +#endif + return f; +} + +static int stbi__start_write_file(stbi__write_context *s, const char *filename) +{ + FILE *f = stbiw__fopen(filename, "wb"); + stbi__start_write_callbacks(s, stbi__stdio_write, (void *) f); + return f != NULL; +} + +static void stbi__end_write_file(stbi__write_context *s) +{ + fclose((FILE *)s->context); +} + +#endif // !STBI_WRITE_NO_STDIO + +typedef unsigned int stbiw_uint32; +typedef int stb_image_write_test[sizeof(stbiw_uint32)==4 ? 1 : -1]; + +static void stbiw__writefv(stbi__write_context *s, const char *fmt, va_list v) +{ + while (*fmt) { + switch (*fmt++) { + case ' ': break; + case '1': { unsigned char x = STBIW_UCHAR(va_arg(v, int)); + s->func(s->context,&x,1); + break; } + case '2': { int x = va_arg(v,int); + unsigned char b[2]; + b[0] = STBIW_UCHAR(x); + b[1] = STBIW_UCHAR(x>>8); + s->func(s->context,b,2); + break; } + case '4': { stbiw_uint32 x = va_arg(v,int); + unsigned char b[4]; + b[0]=STBIW_UCHAR(x); + b[1]=STBIW_UCHAR(x>>8); + b[2]=STBIW_UCHAR(x>>16); + b[3]=STBIW_UCHAR(x>>24); + s->func(s->context,b,4); + break; } + default: + STBIW_ASSERT(0); + return; + } + } +} + +static void stbiw__writef(stbi__write_context *s, const char *fmt, ...) +{ + va_list v; + va_start(v, fmt); + stbiw__writefv(s, fmt, v); + va_end(v); +} + +static void stbiw__putc(stbi__write_context *s, unsigned char c) +{ + s->func(s->context, &c, 1); +} + +static void stbiw__write3(stbi__write_context *s, unsigned char a, unsigned char b, unsigned char c) +{ + unsigned char arr[3]; + arr[0] = a; arr[1] = b; arr[2] = c; + s->func(s->context, arr, 3); +} + +static void stbiw__write_pixel(stbi__write_context *s, int rgb_dir, int comp, int write_alpha, int expand_mono, unsigned char *d) +{ + unsigned char bg[3] = { 255, 0, 255}, px[3]; + int k; + + if (write_alpha < 0) + s->func(s->context, &d[comp - 1], 1); + + switch (comp) { + case 2: // 2 pixels = mono + alpha, alpha is written separately, so same as 1-channel case + case 1: + if (expand_mono) + stbiw__write3(s, d[0], d[0], d[0]); // monochrome bmp + else + s->func(s->context, d, 1); // monochrome TGA + break; + case 4: + if (!write_alpha) { + // composite against pink background + for (k = 0; k < 3; ++k) + px[k] = bg[k] + ((d[k] - bg[k]) * d[3]) / 255; + stbiw__write3(s, px[1 - rgb_dir], px[1], px[1 + rgb_dir]); + break; + } + /* FALLTHROUGH */ + case 3: + stbiw__write3(s, d[1 - rgb_dir], d[1], d[1 + rgb_dir]); + break; + } + if (write_alpha > 0) + s->func(s->context, &d[comp - 1], 1); +} + +static void stbiw__write_pixels(stbi__write_context *s, int rgb_dir, int vdir, int x, int y, int comp, void *data, int write_alpha, int scanline_pad, int expand_mono) +{ + stbiw_uint32 zero = 0; + int i,j, j_end; + + if (y <= 0) + return; + + if (stbi__flip_vertically_on_write) + vdir *= -1; + + if (vdir < 0) { + j_end = -1; j = y-1; + } else { + j_end = y; j = 0; + } + + for (; j != j_end; j += vdir) { + for (i=0; i < x; ++i) { + unsigned char *d = (unsigned char *) data + (j*x+i)*comp; + stbiw__write_pixel(s, rgb_dir, comp, write_alpha, expand_mono, d); + } + s->func(s->context, &zero, scanline_pad); + } +} + +static int stbiw__outfile(stbi__write_context *s, int rgb_dir, int vdir, int x, int y, int comp, int expand_mono, void *data, int alpha, int pad, const char *fmt, ...) +{ + if (y < 0 || x < 0) { + return 0; + } else { + va_list v; + va_start(v, fmt); + stbiw__writefv(s, fmt, v); + va_end(v); + stbiw__write_pixels(s,rgb_dir,vdir,x,y,comp,data,alpha,pad, expand_mono); + return 1; + } +} + +static int stbi_write_bmp_core(stbi__write_context *s, int x, int y, int comp, const void *data) +{ + int pad = (-x*3) & 3; + return stbiw__outfile(s,-1,-1,x,y,comp,1,(void *) data,0,pad, + "11 4 22 4" "4 44 22 444444", + 'B', 'M', 14+40+(x*3+pad)*y, 0,0, 14+40, // file header + 40, x,y, 1,24, 0,0,0,0,0,0); // bitmap header +} + +STBIWDEF int stbi_write_bmp_to_func(stbi_write_func *func, void *context, int x, int y, int comp, const void *data) +{ + stbi__write_context s; + stbi__start_write_callbacks(&s, func, context); + return stbi_write_bmp_core(&s, x, y, comp, data); +} + +#ifndef STBI_WRITE_NO_STDIO +STBIWDEF int stbi_write_bmp(char const *filename, int x, int y, int comp, const void *data) +{ + stbi__write_context s; + if (stbi__start_write_file(&s,filename)) { + int r = stbi_write_bmp_core(&s, x, y, comp, data); + stbi__end_write_file(&s); + return r; + } else + return 0; +} +#endif //!STBI_WRITE_NO_STDIO + +static int stbi_write_tga_core(stbi__write_context *s, int x, int y, int comp, void *data) +{ + int has_alpha = (comp == 2 || comp == 4); + int colorbytes = has_alpha ? comp-1 : comp; + int format = colorbytes < 2 ? 3 : 2; // 3 color channels (RGB/RGBA) = 2, 1 color channel (Y/YA) = 3 + + if (y < 0 || x < 0) + return 0; + + if (!stbi_write_tga_with_rle) { + return stbiw__outfile(s, -1, -1, x, y, comp, 0, (void *) data, has_alpha, 0, + "111 221 2222 11", 0, 0, format, 0, 0, 0, 0, 0, x, y, (colorbytes + has_alpha) * 8, has_alpha * 8); + } else { + int i,j,k; + int jend, jdir; + + stbiw__writef(s, "111 221 2222 11", 0,0,format+8, 0,0,0, 0,0,x,y, (colorbytes + has_alpha) * 8, has_alpha * 8); + + if (stbi__flip_vertically_on_write) { + j = 0; + jend = y; + jdir = 1; + } else { + j = y-1; + jend = -1; + jdir = -1; + } + for (; j != jend; j += jdir) { + unsigned char *row = (unsigned char *) data + j * x * comp; + int len; + + for (i = 0; i < x; i += len) { + unsigned char *begin = row + i * comp; + int diff = 1; + len = 1; + + if (i < x - 1) { + ++len; + diff = memcmp(begin, row + (i + 1) * comp, comp); + if (diff) { + const unsigned char *prev = begin; + for (k = i + 2; k < x && len < 128; ++k) { + if (memcmp(prev, row + k * comp, comp)) { + prev += comp; + ++len; + } else { + --len; + break; + } + } + } else { + for (k = i + 2; k < x && len < 128; ++k) { + if (!memcmp(begin, row + k * comp, comp)) { + ++len; + } else { + break; + } + } + } + } + + if (diff) { + unsigned char header = STBIW_UCHAR(len - 1); + s->func(s->context, &header, 1); + for (k = 0; k < len; ++k) { + stbiw__write_pixel(s, -1, comp, has_alpha, 0, begin + k * comp); + } + } else { + unsigned char header = STBIW_UCHAR(len - 129); + s->func(s->context, &header, 1); + stbiw__write_pixel(s, -1, comp, has_alpha, 0, begin); + } + } + } + } + return 1; +} + +STBIWDEF int stbi_write_tga_to_func(stbi_write_func *func, void *context, int x, int y, int comp, const void *data) +{ + stbi__write_context s; + stbi__start_write_callbacks(&s, func, context); + return stbi_write_tga_core(&s, x, y, comp, (void *) data); +} + +#ifndef STBI_WRITE_NO_STDIO +STBIWDEF int stbi_write_tga(char const *filename, int x, int y, int comp, const void *data) +{ + stbi__write_context s; + if (stbi__start_write_file(&s,filename)) { + int r = stbi_write_tga_core(&s, x, y, comp, (void *) data); + stbi__end_write_file(&s); + return r; + } else + return 0; +} +#endif + +// ************************************************************************************************* +// Radiance RGBE HDR writer +// by Baldur Karlsson + +#define stbiw__max(a, b) ((a) > (b) ? (a) : (b)) + +static void stbiw__linear_to_rgbe(unsigned char *rgbe, float *linear) +{ + int exponent; + float maxcomp = stbiw__max(linear[0], stbiw__max(linear[1], linear[2])); + + if (maxcomp < 1e-32f) { + rgbe[0] = rgbe[1] = rgbe[2] = rgbe[3] = 0; + } else { + float normalize = (float) frexp(maxcomp, &exponent) * 256.0f/maxcomp; + + rgbe[0] = (unsigned char)(linear[0] * normalize); + rgbe[1] = (unsigned char)(linear[1] * normalize); + rgbe[2] = (unsigned char)(linear[2] * normalize); + rgbe[3] = (unsigned char)(exponent + 128); + } +} + +static void stbiw__write_run_data(stbi__write_context *s, int length, unsigned char databyte) +{ + unsigned char lengthbyte = STBIW_UCHAR(length+128); + STBIW_ASSERT(length+128 <= 255); + s->func(s->context, &lengthbyte, 1); + s->func(s->context, &databyte, 1); +} + +static void stbiw__write_dump_data(stbi__write_context *s, int length, unsigned char *data) +{ + unsigned char lengthbyte = STBIW_UCHAR(length); + STBIW_ASSERT(length <= 128); // inconsistent with spec but consistent with official code + s->func(s->context, &lengthbyte, 1); + s->func(s->context, data, length); +} + +static void stbiw__write_hdr_scanline(stbi__write_context *s, int width, int ncomp, unsigned char *scratch, float *scanline) +{ + unsigned char scanlineheader[4] = { 2, 2, 0, 0 }; + unsigned char rgbe[4]; + float linear[3]; + int x; + + scanlineheader[2] = (width&0xff00)>>8; + scanlineheader[3] = (width&0x00ff); + + /* skip RLE for images too small or large */ + if (width < 8 || width >= 32768) { + for (x=0; x < width; x++) { + switch (ncomp) { + case 4: /* fallthrough */ + case 3: linear[2] = scanline[x*ncomp + 2]; + linear[1] = scanline[x*ncomp + 1]; + linear[0] = scanline[x*ncomp + 0]; + break; + default: + linear[0] = linear[1] = linear[2] = scanline[x*ncomp + 0]; + break; + } + stbiw__linear_to_rgbe(rgbe, linear); + s->func(s->context, rgbe, 4); + } + } else { + int c,r; + /* encode into scratch buffer */ + for (x=0; x < width; x++) { + switch(ncomp) { + case 4: /* fallthrough */ + case 3: linear[2] = scanline[x*ncomp + 2]; + linear[1] = scanline[x*ncomp + 1]; + linear[0] = scanline[x*ncomp + 0]; + break; + default: + linear[0] = linear[1] = linear[2] = scanline[x*ncomp + 0]; + break; + } + stbiw__linear_to_rgbe(rgbe, linear); + scratch[x + width*0] = rgbe[0]; + scratch[x + width*1] = rgbe[1]; + scratch[x + width*2] = rgbe[2]; + scratch[x + width*3] = rgbe[3]; + } + + s->func(s->context, scanlineheader, 4); + + /* RLE each component separately */ + for (c=0; c < 4; c++) { + unsigned char *comp = &scratch[width*c]; + + x = 0; + while (x < width) { + // find first run + r = x; + while (r+2 < width) { + if (comp[r] == comp[r+1] && comp[r] == comp[r+2]) + break; + ++r; + } + if (r+2 >= width) + r = width; + // dump up to first run + while (x < r) { + int len = r-x; + if (len > 128) len = 128; + stbiw__write_dump_data(s, len, &comp[x]); + x += len; + } + // if there's a run, output it + if (r+2 < width) { // same test as what we break out of in search loop, so only true if we break'd + // find next byte after run + while (r < width && comp[r] == comp[x]) + ++r; + // output run up to r + while (x < r) { + int len = r-x; + if (len > 127) len = 127; + stbiw__write_run_data(s, len, comp[x]); + x += len; + } + } + } + } + } +} + +static int stbi_write_hdr_core(stbi__write_context *s, int x, int y, int comp, float *data) +{ + if (y <= 0 || x <= 0 || data == NULL) + return 0; + else { + // Each component is stored separately. Allocate scratch space for full output scanline. + unsigned char *scratch = (unsigned char *) STBIW_MALLOC(x*4); + int i, len; + char buffer[128]; + char header[] = "#?RADIANCE\n# Written by stb_image_write.h\nFORMAT=32-bit_rle_rgbe\n"; + s->func(s->context, header, sizeof(header)-1); + +#ifdef __STDC_WANT_SECURE_LIB__ + len = sprintf_s(buffer, sizeof(buffer), "EXPOSURE= 1.0000000000000\n\n-Y %d +X %d\n", y, x); +#else + len = sprintf(buffer, "EXPOSURE= 1.0000000000000\n\n-Y %d +X %d\n", y, x); +#endif + s->func(s->context, buffer, len); + + for(i=0; i < y; i++) + stbiw__write_hdr_scanline(s, x, comp, scratch, data + comp*x*(stbi__flip_vertically_on_write ? y-1-i : i)); + STBIW_FREE(scratch); + return 1; + } +} + +STBIWDEF int stbi_write_hdr_to_func(stbi_write_func *func, void *context, int x, int y, int comp, const float *data) +{ + stbi__write_context s; + stbi__start_write_callbacks(&s, func, context); + return stbi_write_hdr_core(&s, x, y, comp, (float *) data); +} + +#ifndef STBI_WRITE_NO_STDIO +STBIWDEF int stbi_write_hdr(char const *filename, int x, int y, int comp, const float *data) +{ + stbi__write_context s; + if (stbi__start_write_file(&s,filename)) { + int r = stbi_write_hdr_core(&s, x, y, comp, (float *) data); + stbi__end_write_file(&s); + return r; + } else + return 0; +} +#endif // STBI_WRITE_NO_STDIO + + +////////////////////////////////////////////////////////////////////////////// +// +// PNG writer +// + +#ifndef STBIW_ZLIB_COMPRESS +// stretchy buffer; stbiw__sbpush() == vector<>::push_back() -- stbiw__sbcount() == vector<>::size() +#define stbiw__sbraw(a) ((int *) (void *) (a) - 2) +#define stbiw__sbm(a) stbiw__sbraw(a)[0] +#define stbiw__sbn(a) stbiw__sbraw(a)[1] + +#define stbiw__sbneedgrow(a,n) ((a)==0 || stbiw__sbn(a)+n >= stbiw__sbm(a)) +#define stbiw__sbmaybegrow(a,n) (stbiw__sbneedgrow(a,(n)) ? stbiw__sbgrow(a,n) : 0) +#define stbiw__sbgrow(a,n) stbiw__sbgrowf((void **) &(a), (n), sizeof(*(a))) + +#define stbiw__sbpush(a, v) (stbiw__sbmaybegrow(a,1), (a)[stbiw__sbn(a)++] = (v)) +#define stbiw__sbcount(a) ((a) ? stbiw__sbn(a) : 0) +#define stbiw__sbfree(a) ((a) ? STBIW_FREE(stbiw__sbraw(a)),0 : 0) + +static void *stbiw__sbgrowf(void **arr, int increment, int itemsize) +{ + int m = *arr ? 2*stbiw__sbm(*arr)+increment : increment+1; + void *p = STBIW_REALLOC_SIZED(*arr ? stbiw__sbraw(*arr) : 0, *arr ? (stbiw__sbm(*arr)*itemsize + sizeof(int)*2) : 0, itemsize * m + sizeof(int)*2); + STBIW_ASSERT(p); + if (p) { + if (!*arr) ((int *) p)[1] = 0; + *arr = (void *) ((int *) p + 2); + stbiw__sbm(*arr) = m; + } + return *arr; +} + +static unsigned char *stbiw__zlib_flushf(unsigned char *data, unsigned int *bitbuffer, int *bitcount) +{ + while (*bitcount >= 8) { + stbiw__sbpush(data, STBIW_UCHAR(*bitbuffer)); + *bitbuffer >>= 8; + *bitcount -= 8; + } + return data; +} + +static int stbiw__zlib_bitrev(int code, int codebits) +{ + int res=0; + while (codebits--) { + res = (res << 1) | (code & 1); + code >>= 1; + } + return res; +} + +static unsigned int stbiw__zlib_countm(unsigned char *a, unsigned char *b, int limit) +{ + int i; + for (i=0; i < limit && i < 258; ++i) + if (a[i] != b[i]) break; + return i; +} + +static unsigned int stbiw__zhash(unsigned char *data) +{ + stbiw_uint32 hash = data[0] + (data[1] << 8) + (data[2] << 16); + hash ^= hash << 3; + hash += hash >> 5; + hash ^= hash << 4; + hash += hash >> 17; + hash ^= hash << 25; + hash += hash >> 6; + return hash; +} + +#define stbiw__zlib_flush() (out = stbiw__zlib_flushf(out, &bitbuf, &bitcount)) +#define stbiw__zlib_add(code,codebits) \ + (bitbuf |= (code) << bitcount, bitcount += (codebits), stbiw__zlib_flush()) +#define stbiw__zlib_huffa(b,c) stbiw__zlib_add(stbiw__zlib_bitrev(b,c),c) +// default huffman tables +#define stbiw__zlib_huff1(n) stbiw__zlib_huffa(0x30 + (n), 8) +#define stbiw__zlib_huff2(n) stbiw__zlib_huffa(0x190 + (n)-144, 9) +#define stbiw__zlib_huff3(n) stbiw__zlib_huffa(0 + (n)-256,7) +#define stbiw__zlib_huff4(n) stbiw__zlib_huffa(0xc0 + (n)-280,8) +#define stbiw__zlib_huff(n) ((n) <= 143 ? stbiw__zlib_huff1(n) : (n) <= 255 ? stbiw__zlib_huff2(n) : (n) <= 279 ? stbiw__zlib_huff3(n) : stbiw__zlib_huff4(n)) +#define stbiw__zlib_huffb(n) ((n) <= 143 ? stbiw__zlib_huff1(n) : stbiw__zlib_huff2(n)) + +#define stbiw__ZHASH 16384 + +#endif // STBIW_ZLIB_COMPRESS + +STBIWDEF unsigned char * stbi_zlib_compress(unsigned char *data, int data_len, int *out_len, int quality) +{ +#ifdef STBIW_ZLIB_COMPRESS + // user provided a zlib compress implementation, use that + return STBIW_ZLIB_COMPRESS(data, data_len, out_len, quality); +#else // use builtin + static unsigned short lengthc[] = { 3,4,5,6,7,8,9,10,11,13,15,17,19,23,27,31,35,43,51,59,67,83,99,115,131,163,195,227,258, 259 }; + static unsigned char lengtheb[]= { 0,0,0,0,0,0,0, 0, 1, 1, 1, 1, 2, 2, 2, 2, 3, 3, 3, 3, 4, 4, 4, 4, 5, 5, 5, 5, 0 }; + static unsigned short distc[] = { 1,2,3,4,5,7,9,13,17,25,33,49,65,97,129,193,257,385,513,769,1025,1537,2049,3073,4097,6145,8193,12289,16385,24577, 32768 }; + static unsigned char disteb[] = { 0,0,0,0,1,1,2,2,3,3,4,4,5,5,6,6,7,7,8,8,9,9,10,10,11,11,12,12,13,13 }; + unsigned int bitbuf=0; + int i,j, bitcount=0; + unsigned char *out = NULL; + unsigned char ***hash_table = (unsigned char***) STBIW_MALLOC(stbiw__ZHASH * sizeof(unsigned char**)); + if (hash_table == NULL) + return NULL; + if (quality < 5) quality = 5; + + stbiw__sbpush(out, 0x78); // DEFLATE 32K window + stbiw__sbpush(out, 0x5e); // FLEVEL = 1 + stbiw__zlib_add(1,1); // BFINAL = 1 + stbiw__zlib_add(1,2); // BTYPE = 1 -- fixed huffman + + for (i=0; i < stbiw__ZHASH; ++i) + hash_table[i] = NULL; + + i=0; + while (i < data_len-3) { + // hash next 3 bytes of data to be compressed + int h = stbiw__zhash(data+i)&(stbiw__ZHASH-1), best=3; + unsigned char *bestloc = 0; + unsigned char **hlist = hash_table[h]; + int n = stbiw__sbcount(hlist); + for (j=0; j < n; ++j) { + if (hlist[j]-data > i-32768) { // if entry lies within window + int d = stbiw__zlib_countm(hlist[j], data+i, data_len-i); + if (d >= best) { best=d; bestloc=hlist[j]; } + } + } + // when hash table entry is too long, delete half the entries + if (hash_table[h] && stbiw__sbn(hash_table[h]) == 2*quality) { + STBIW_MEMMOVE(hash_table[h], hash_table[h]+quality, sizeof(hash_table[h][0])*quality); + stbiw__sbn(hash_table[h]) = quality; + } + stbiw__sbpush(hash_table[h],data+i); + + if (bestloc) { + // "lazy matching" - check match at *next* byte, and if it's better, do cur byte as literal + h = stbiw__zhash(data+i+1)&(stbiw__ZHASH-1); + hlist = hash_table[h]; + n = stbiw__sbcount(hlist); + for (j=0; j < n; ++j) { + if (hlist[j]-data > i-32767) { + int e = stbiw__zlib_countm(hlist[j], data+i+1, data_len-i-1); + if (e > best) { // if next match is better, bail on current match + bestloc = NULL; + break; + } + } + } + } + + if (bestloc) { + int d = (int) (data+i - bestloc); // distance back + STBIW_ASSERT(d <= 32767 && best <= 258); + for (j=0; best > lengthc[j+1]-1; ++j); + stbiw__zlib_huff(j+257); + if (lengtheb[j]) stbiw__zlib_add(best - lengthc[j], lengtheb[j]); + for (j=0; d > distc[j+1]-1; ++j); + stbiw__zlib_add(stbiw__zlib_bitrev(j,5),5); + if (disteb[j]) stbiw__zlib_add(d - distc[j], disteb[j]); + i += best; + } else { + stbiw__zlib_huffb(data[i]); + ++i; + } + } + // write out final bytes + for (;i < data_len; ++i) + stbiw__zlib_huffb(data[i]); + stbiw__zlib_huff(256); // end of block + // pad with 0 bits to byte boundary + while (bitcount) + stbiw__zlib_add(0,1); + + for (i=0; i < stbiw__ZHASH; ++i) + (void) stbiw__sbfree(hash_table[i]); + STBIW_FREE(hash_table); + + { + // compute adler32 on input + unsigned int s1=1, s2=0; + int blocklen = (int) (data_len % 5552); + j=0; + while (j < data_len) { + for (i=0; i < blocklen; ++i) { s1 += data[j+i]; s2 += s1; } + s1 %= 65521; s2 %= 65521; + j += blocklen; + blocklen = 5552; + } + stbiw__sbpush(out, STBIW_UCHAR(s2 >> 8)); + stbiw__sbpush(out, STBIW_UCHAR(s2)); + stbiw__sbpush(out, STBIW_UCHAR(s1 >> 8)); + stbiw__sbpush(out, STBIW_UCHAR(s1)); + } + *out_len = stbiw__sbn(out); + // make returned pointer freeable + STBIW_MEMMOVE(stbiw__sbraw(out), out, *out_len); + return (unsigned char *) stbiw__sbraw(out); +#endif // STBIW_ZLIB_COMPRESS +} + +static unsigned int stbiw__crc32(unsigned char *buffer, int len) +{ +#ifdef STBIW_CRC32 + return STBIW_CRC32(buffer, len); +#else + static unsigned int crc_table[256] = + { + 0x00000000, 0x77073096, 0xEE0E612C, 0x990951BA, 0x076DC419, 0x706AF48F, 0xE963A535, 0x9E6495A3, + 0x0eDB8832, 0x79DCB8A4, 0xE0D5E91E, 0x97D2D988, 0x09B64C2B, 0x7EB17CBD, 0xE7B82D07, 0x90BF1D91, + 0x1DB71064, 0x6AB020F2, 0xF3B97148, 0x84BE41DE, 0x1ADAD47D, 0x6DDDE4EB, 0xF4D4B551, 0x83D385C7, + 0x136C9856, 0x646BA8C0, 0xFD62F97A, 0x8A65C9EC, 0x14015C4F, 0x63066CD9, 0xFA0F3D63, 0x8D080DF5, + 0x3B6E20C8, 0x4C69105E, 0xD56041E4, 0xA2677172, 0x3C03E4D1, 0x4B04D447, 0xD20D85FD, 0xA50AB56B, + 0x35B5A8FA, 0x42B2986C, 0xDBBBC9D6, 0xACBCF940, 0x32D86CE3, 0x45DF5C75, 0xDCD60DCF, 0xABD13D59, + 0x26D930AC, 0x51DE003A, 0xC8D75180, 0xBFD06116, 0x21B4F4B5, 0x56B3C423, 0xCFBA9599, 0xB8BDA50F, + 0x2802B89E, 0x5F058808, 0xC60CD9B2, 0xB10BE924, 0x2F6F7C87, 0x58684C11, 0xC1611DAB, 0xB6662D3D, + 0x76DC4190, 0x01DB7106, 0x98D220BC, 0xEFD5102A, 0x71B18589, 0x06B6B51F, 0x9FBFE4A5, 0xE8B8D433, + 0x7807C9A2, 0x0F00F934, 0x9609A88E, 0xE10E9818, 0x7F6A0DBB, 0x086D3D2D, 0x91646C97, 0xE6635C01, + 0x6B6B51F4, 0x1C6C6162, 0x856530D8, 0xF262004E, 0x6C0695ED, 0x1B01A57B, 0x8208F4C1, 0xF50FC457, + 0x65B0D9C6, 0x12B7E950, 0x8BBEB8EA, 0xFCB9887C, 0x62DD1DDF, 0x15DA2D49, 0x8CD37CF3, 0xFBD44C65, + 0x4DB26158, 0x3AB551CE, 0xA3BC0074, 0xD4BB30E2, 0x4ADFA541, 0x3DD895D7, 0xA4D1C46D, 0xD3D6F4FB, + 0x4369E96A, 0x346ED9FC, 0xAD678846, 0xDA60B8D0, 0x44042D73, 0x33031DE5, 0xAA0A4C5F, 0xDD0D7CC9, + 0x5005713C, 0x270241AA, 0xBE0B1010, 0xC90C2086, 0x5768B525, 0x206F85B3, 0xB966D409, 0xCE61E49F, + 0x5EDEF90E, 0x29D9C998, 0xB0D09822, 0xC7D7A8B4, 0x59B33D17, 0x2EB40D81, 0xB7BD5C3B, 0xC0BA6CAD, + 0xEDB88320, 0x9ABFB3B6, 0x03B6E20C, 0x74B1D29A, 0xEAD54739, 0x9DD277AF, 0x04DB2615, 0x73DC1683, + 0xE3630B12, 0x94643B84, 0x0D6D6A3E, 0x7A6A5AA8, 0xE40ECF0B, 0x9309FF9D, 0x0A00AE27, 0x7D079EB1, + 0xF00F9344, 0x8708A3D2, 0x1E01F268, 0x6906C2FE, 0xF762575D, 0x806567CB, 0x196C3671, 0x6E6B06E7, + 0xFED41B76, 0x89D32BE0, 0x10DA7A5A, 0x67DD4ACC, 0xF9B9DF6F, 0x8EBEEFF9, 0x17B7BE43, 0x60B08ED5, + 0xD6D6A3E8, 0xA1D1937E, 0x38D8C2C4, 0x4FDFF252, 0xD1BB67F1, 0xA6BC5767, 0x3FB506DD, 0x48B2364B, + 0xD80D2BDA, 0xAF0A1B4C, 0x36034AF6, 0x41047A60, 0xDF60EFC3, 0xA867DF55, 0x316E8EEF, 0x4669BE79, + 0xCB61B38C, 0xBC66831A, 0x256FD2A0, 0x5268E236, 0xCC0C7795, 0xBB0B4703, 0x220216B9, 0x5505262F, + 0xC5BA3BBE, 0xB2BD0B28, 0x2BB45A92, 0x5CB36A04, 0xC2D7FFA7, 0xB5D0CF31, 0x2CD99E8B, 0x5BDEAE1D, + 0x9B64C2B0, 0xEC63F226, 0x756AA39C, 0x026D930A, 0x9C0906A9, 0xEB0E363F, 0x72076785, 0x05005713, + 0x95BF4A82, 0xE2B87A14, 0x7BB12BAE, 0x0CB61B38, 0x92D28E9B, 0xE5D5BE0D, 0x7CDCEFB7, 0x0BDBDF21, + 0x86D3D2D4, 0xF1D4E242, 0x68DDB3F8, 0x1FDA836E, 0x81BE16CD, 0xF6B9265B, 0x6FB077E1, 0x18B74777, + 0x88085AE6, 0xFF0F6A70, 0x66063BCA, 0x11010B5C, 0x8F659EFF, 0xF862AE69, 0x616BFFD3, 0x166CCF45, + 0xA00AE278, 0xD70DD2EE, 0x4E048354, 0x3903B3C2, 0xA7672661, 0xD06016F7, 0x4969474D, 0x3E6E77DB, + 0xAED16A4A, 0xD9D65ADC, 0x40DF0B66, 0x37D83BF0, 0xA9BCAE53, 0xDEBB9EC5, 0x47B2CF7F, 0x30B5FFE9, + 0xBDBDF21C, 0xCABAC28A, 0x53B39330, 0x24B4A3A6, 0xBAD03605, 0xCDD70693, 0x54DE5729, 0x23D967BF, + 0xB3667A2E, 0xC4614AB8, 0x5D681B02, 0x2A6F2B94, 0xB40BBE37, 0xC30C8EA1, 0x5A05DF1B, 0x2D02EF8D + }; + + unsigned int crc = ~0u; + int i; + for (i=0; i < len; ++i) + crc = (crc >> 8) ^ crc_table[buffer[i] ^ (crc & 0xff)]; + return ~crc; +#endif +} + +#define stbiw__wpng4(o,a,b,c,d) ((o)[0]=STBIW_UCHAR(a),(o)[1]=STBIW_UCHAR(b),(o)[2]=STBIW_UCHAR(c),(o)[3]=STBIW_UCHAR(d),(o)+=4) +#define stbiw__wp32(data,v) stbiw__wpng4(data, (v)>>24,(v)>>16,(v)>>8,(v)); +#define stbiw__wptag(data,s) stbiw__wpng4(data, s[0],s[1],s[2],s[3]) + +static void stbiw__wpcrc(unsigned char **data, int len) +{ + unsigned int crc = stbiw__crc32(*data - len - 4, len+4); + stbiw__wp32(*data, crc); +} + +static unsigned char stbiw__paeth(int a, int b, int c) +{ + int p = a + b - c, pa = abs(p-a), pb = abs(p-b), pc = abs(p-c); + if (pa <= pb && pa <= pc) return STBIW_UCHAR(a); + if (pb <= pc) return STBIW_UCHAR(b); + return STBIW_UCHAR(c); +} + +// @OPTIMIZE: provide an option that always forces left-predict or paeth predict +static void stbiw__encode_png_line(unsigned char *pixels, int stride_bytes, int width, int height, int y, int n, int filter_type, signed char *line_buffer) +{ + static int mapping[] = { 0,1,2,3,4 }; + static int firstmap[] = { 0,1,0,5,6 }; + int *mymap = (y != 0) ? mapping : firstmap; + int i; + int type = mymap[filter_type]; + unsigned char *z = pixels + stride_bytes * (stbi__flip_vertically_on_write ? height-1-y : y); + int signed_stride = stbi__flip_vertically_on_write ? -stride_bytes : stride_bytes; + + if (type==0) { + memcpy(line_buffer, z, width*n); + return; + } + + // first loop isn't optimized since it's just one pixel + for (i = 0; i < n; ++i) { + switch (type) { + case 1: line_buffer[i] = z[i]; break; + case 2: line_buffer[i] = z[i] - z[i-signed_stride]; break; + case 3: line_buffer[i] = z[i] - (z[i-signed_stride]>>1); break; + case 4: line_buffer[i] = (signed char) (z[i] - stbiw__paeth(0,z[i-signed_stride],0)); break; + case 5: line_buffer[i] = z[i]; break; + case 6: line_buffer[i] = z[i]; break; + } + } + switch (type) { + case 1: for (i=n; i < width*n; ++i) line_buffer[i] = z[i] - z[i-n]; break; + case 2: for (i=n; i < width*n; ++i) line_buffer[i] = z[i] - z[i-signed_stride]; break; + case 3: for (i=n; i < width*n; ++i) line_buffer[i] = z[i] - ((z[i-n] + z[i-signed_stride])>>1); break; + case 4: for (i=n; i < width*n; ++i) line_buffer[i] = z[i] - stbiw__paeth(z[i-n], z[i-signed_stride], z[i-signed_stride-n]); break; + case 5: for (i=n; i < width*n; ++i) line_buffer[i] = z[i] - (z[i-n]>>1); break; + case 6: for (i=n; i < width*n; ++i) line_buffer[i] = z[i] - stbiw__paeth(z[i-n], 0,0); break; + } +} + +STBIWDEF unsigned char *stbi_write_png_to_mem(const unsigned char *pixels, int stride_bytes, int x, int y, int n, int *out_len) +{ + int force_filter = stbi_write_force_png_filter; + int ctype[5] = { -1, 0, 4, 2, 6 }; + unsigned char sig[8] = { 137,80,78,71,13,10,26,10 }; + unsigned char *out,*o, *filt, *zlib; + signed char *line_buffer; + int j,zlen; + + if (stride_bytes == 0) + stride_bytes = x * n; + + if (force_filter >= 5) { + force_filter = -1; + } + + filt = (unsigned char *) STBIW_MALLOC((x*n+1) * y); if (!filt) return 0; + line_buffer = (signed char *) STBIW_MALLOC(x * n); if (!line_buffer) { STBIW_FREE(filt); return 0; } + for (j=0; j < y; ++j) { + int filter_type; + if (force_filter > -1) { + filter_type = force_filter; + stbiw__encode_png_line((unsigned char*)(pixels), stride_bytes, x, y, j, n, force_filter, line_buffer); + } else { // Estimate the best filter by running through all of them: + int best_filter = 0, best_filter_val = 0x7fffffff, est, i; + for (filter_type = 0; filter_type < 5; filter_type++) { + stbiw__encode_png_line((unsigned char*)(pixels), stride_bytes, x, y, j, n, filter_type, line_buffer); + + // Estimate the entropy of the line using this filter; the less, the better. + est = 0; + for (i = 0; i < x*n; ++i) { + est += abs((signed char) line_buffer[i]); + } + if (est < best_filter_val) { + best_filter_val = est; + best_filter = filter_type; + } + } + if (filter_type != best_filter) { // If the last iteration already got us the best filter, don't redo it + stbiw__encode_png_line((unsigned char*)(pixels), stride_bytes, x, y, j, n, best_filter, line_buffer); + filter_type = best_filter; + } + } + // when we get here, filter_type contains the filter type, and line_buffer contains the data + filt[j*(x*n+1)] = (unsigned char) filter_type; + STBIW_MEMMOVE(filt+j*(x*n+1)+1, line_buffer, x*n); + } + STBIW_FREE(line_buffer); + zlib = stbi_zlib_compress(filt, y*( x*n+1), &zlen, stbi_write_png_compression_level); + STBIW_FREE(filt); + if (!zlib) return 0; + + // each tag requires 12 bytes of overhead + out = (unsigned char *) STBIW_MALLOC(8 + 12+13 + 12+zlen + 12); + if (!out) return 0; + *out_len = 8 + 12+13 + 12+zlen + 12; + + o=out; + STBIW_MEMMOVE(o,sig,8); o+= 8; + stbiw__wp32(o, 13); // header length + stbiw__wptag(o, "IHDR"); + stbiw__wp32(o, x); + stbiw__wp32(o, y); + *o++ = 8; + *o++ = STBIW_UCHAR(ctype[n]); + *o++ = 0; + *o++ = 0; + *o++ = 0; + stbiw__wpcrc(&o,13); + + stbiw__wp32(o, zlen); + stbiw__wptag(o, "IDAT"); + STBIW_MEMMOVE(o, zlib, zlen); + o += zlen; + STBIW_FREE(zlib); + stbiw__wpcrc(&o, zlen); + + stbiw__wp32(o,0); + stbiw__wptag(o, "IEND"); + stbiw__wpcrc(&o,0); + + STBIW_ASSERT(o == out + *out_len); + + return out; +} + +#ifndef STBI_WRITE_NO_STDIO +STBIWDEF int stbi_write_png(char const *filename, int x, int y, int comp, const void *data, int stride_bytes) +{ + FILE *f; + int len; + unsigned char *png = stbi_write_png_to_mem((const unsigned char *) data, stride_bytes, x, y, comp, &len); + if (png == NULL) return 0; + + f = stbiw__fopen(filename, "wb"); + if (!f) { STBIW_FREE(png); return 0; } + fwrite(png, 1, len, f); + fclose(f); + STBIW_FREE(png); + return 1; +} +#endif + +STBIWDEF int stbi_write_png_to_func(stbi_write_func *func, void *context, int x, int y, int comp, const void *data, int stride_bytes) +{ + int len; + unsigned char *png = stbi_write_png_to_mem((const unsigned char *) data, stride_bytes, x, y, comp, &len); + if (png == NULL) return 0; + func(context, png, len); + STBIW_FREE(png); + return 1; +} + + +/* *************************************************************************** + * + * JPEG writer + * + * This is based on Jon Olick's jo_jpeg.cpp: + * public domain Simple, Minimalistic JPEG writer - http://www.jonolick.com/code.html + */ + +static const unsigned char stbiw__jpg_ZigZag[] = { 0,1,5,6,14,15,27,28,2,4,7,13,16,26,29,42,3,8,12,17,25,30,41,43,9,11,18, + 24,31,40,44,53,10,19,23,32,39,45,52,54,20,22,33,38,46,51,55,60,21,34,37,47,50,56,59,61,35,36,48,49,57,58,62,63 }; + +static void stbiw__jpg_writeBits(stbi__write_context *s, int *bitBufP, int *bitCntP, const unsigned short *bs) { + int bitBuf = *bitBufP, bitCnt = *bitCntP; + bitCnt += bs[1]; + bitBuf |= bs[0] << (24 - bitCnt); + while(bitCnt >= 8) { + unsigned char c = (bitBuf >> 16) & 255; + stbiw__putc(s, c); + if(c == 255) { + stbiw__putc(s, 0); + } + bitBuf <<= 8; + bitCnt -= 8; + } + *bitBufP = bitBuf; + *bitCntP = bitCnt; +} + +static void stbiw__jpg_DCT(float *d0p, float *d1p, float *d2p, float *d3p, float *d4p, float *d5p, float *d6p, float *d7p) { + float d0 = *d0p, d1 = *d1p, d2 = *d2p, d3 = *d3p, d4 = *d4p, d5 = *d5p, d6 = *d6p, d7 = *d7p; + float z1, z2, z3, z4, z5, z11, z13; + + float tmp0 = d0 + d7; + float tmp7 = d0 - d7; + float tmp1 = d1 + d6; + float tmp6 = d1 - d6; + float tmp2 = d2 + d5; + float tmp5 = d2 - d5; + float tmp3 = d3 + d4; + float tmp4 = d3 - d4; + + // Even part + float tmp10 = tmp0 + tmp3; // phase 2 + float tmp13 = tmp0 - tmp3; + float tmp11 = tmp1 + tmp2; + float tmp12 = tmp1 - tmp2; + + d0 = tmp10 + tmp11; // phase 3 + d4 = tmp10 - tmp11; + + z1 = (tmp12 + tmp13) * 0.707106781f; // c4 + d2 = tmp13 + z1; // phase 5 + d6 = tmp13 - z1; + + // Odd part + tmp10 = tmp4 + tmp5; // phase 2 + tmp11 = tmp5 + tmp6; + tmp12 = tmp6 + tmp7; + + // The rotator is modified from fig 4-8 to avoid extra negations. + z5 = (tmp10 - tmp12) * 0.382683433f; // c6 + z2 = tmp10 * 0.541196100f + z5; // c2-c6 + z4 = tmp12 * 1.306562965f + z5; // c2+c6 + z3 = tmp11 * 0.707106781f; // c4 + + z11 = tmp7 + z3; // phase 5 + z13 = tmp7 - z3; + + *d5p = z13 + z2; // phase 6 + *d3p = z13 - z2; + *d1p = z11 + z4; + *d7p = z11 - z4; + + *d0p = d0; *d2p = d2; *d4p = d4; *d6p = d6; +} + +static void stbiw__jpg_calcBits(int val, unsigned short bits[2]) { + int tmp1 = val < 0 ? -val : val; + val = val < 0 ? val-1 : val; + bits[1] = 1; + while(tmp1 >>= 1) { + ++bits[1]; + } + bits[0] = val & ((1<0)&&(DU[end0pos]==0); --end0pos) { + } + // end0pos = first element in reverse order !=0 + if(end0pos == 0) { + stbiw__jpg_writeBits(s, bitBuf, bitCnt, EOB); + return DU[0]; + } + for(i = 1; i <= end0pos; ++i) { + int startpos = i; + int nrzeroes; + unsigned short bits[2]; + for (; DU[i]==0 && i<=end0pos; ++i) { + } + nrzeroes = i-startpos; + if ( nrzeroes >= 16 ) { + int lng = nrzeroes>>4; + int nrmarker; + for (nrmarker=1; nrmarker <= lng; ++nrmarker) + stbiw__jpg_writeBits(s, bitBuf, bitCnt, M16zeroes); + nrzeroes &= 15; + } + stbiw__jpg_calcBits(DU[i], bits); + stbiw__jpg_writeBits(s, bitBuf, bitCnt, HTAC[(nrzeroes<<4)+bits[1]]); + stbiw__jpg_writeBits(s, bitBuf, bitCnt, bits); + } + if(end0pos != 63) { + stbiw__jpg_writeBits(s, bitBuf, bitCnt, EOB); + } + return DU[0]; +} + +static int stbi_write_jpg_core(stbi__write_context *s, int width, int height, int comp, const void* data, int quality) { + // Constants that don't pollute global namespace + static const unsigned char std_dc_luminance_nrcodes[] = {0,0,1,5,1,1,1,1,1,1,0,0,0,0,0,0,0}; + static const unsigned char std_dc_luminance_values[] = {0,1,2,3,4,5,6,7,8,9,10,11}; + static const unsigned char std_ac_luminance_nrcodes[] = {0,0,2,1,3,3,2,4,3,5,5,4,4,0,0,1,0x7d}; + static const unsigned char std_ac_luminance_values[] = { + 0x01,0x02,0x03,0x00,0x04,0x11,0x05,0x12,0x21,0x31,0x41,0x06,0x13,0x51,0x61,0x07,0x22,0x71,0x14,0x32,0x81,0x91,0xa1,0x08, + 0x23,0x42,0xb1,0xc1,0x15,0x52,0xd1,0xf0,0x24,0x33,0x62,0x72,0x82,0x09,0x0a,0x16,0x17,0x18,0x19,0x1a,0x25,0x26,0x27,0x28, + 0x29,0x2a,0x34,0x35,0x36,0x37,0x38,0x39,0x3a,0x43,0x44,0x45,0x46,0x47,0x48,0x49,0x4a,0x53,0x54,0x55,0x56,0x57,0x58,0x59, + 0x5a,0x63,0x64,0x65,0x66,0x67,0x68,0x69,0x6a,0x73,0x74,0x75,0x76,0x77,0x78,0x79,0x7a,0x83,0x84,0x85,0x86,0x87,0x88,0x89, + 0x8a,0x92,0x93,0x94,0x95,0x96,0x97,0x98,0x99,0x9a,0xa2,0xa3,0xa4,0xa5,0xa6,0xa7,0xa8,0xa9,0xaa,0xb2,0xb3,0xb4,0xb5,0xb6, + 0xb7,0xb8,0xb9,0xba,0xc2,0xc3,0xc4,0xc5,0xc6,0xc7,0xc8,0xc9,0xca,0xd2,0xd3,0xd4,0xd5,0xd6,0xd7,0xd8,0xd9,0xda,0xe1,0xe2, + 0xe3,0xe4,0xe5,0xe6,0xe7,0xe8,0xe9,0xea,0xf1,0xf2,0xf3,0xf4,0xf5,0xf6,0xf7,0xf8,0xf9,0xfa + }; + static const unsigned char std_dc_chrominance_nrcodes[] = {0,0,3,1,1,1,1,1,1,1,1,1,0,0,0,0,0}; + static const unsigned char std_dc_chrominance_values[] = {0,1,2,3,4,5,6,7,8,9,10,11}; + static const unsigned char std_ac_chrominance_nrcodes[] = {0,0,2,1,2,4,4,3,4,7,5,4,4,0,1,2,0x77}; + static const unsigned char std_ac_chrominance_values[] = { + 0x00,0x01,0x02,0x03,0x11,0x04,0x05,0x21,0x31,0x06,0x12,0x41,0x51,0x07,0x61,0x71,0x13,0x22,0x32,0x81,0x08,0x14,0x42,0x91, + 0xa1,0xb1,0xc1,0x09,0x23,0x33,0x52,0xf0,0x15,0x62,0x72,0xd1,0x0a,0x16,0x24,0x34,0xe1,0x25,0xf1,0x17,0x18,0x19,0x1a,0x26, + 0x27,0x28,0x29,0x2a,0x35,0x36,0x37,0x38,0x39,0x3a,0x43,0x44,0x45,0x46,0x47,0x48,0x49,0x4a,0x53,0x54,0x55,0x56,0x57,0x58, + 0x59,0x5a,0x63,0x64,0x65,0x66,0x67,0x68,0x69,0x6a,0x73,0x74,0x75,0x76,0x77,0x78,0x79,0x7a,0x82,0x83,0x84,0x85,0x86,0x87, + 0x88,0x89,0x8a,0x92,0x93,0x94,0x95,0x96,0x97,0x98,0x99,0x9a,0xa2,0xa3,0xa4,0xa5,0xa6,0xa7,0xa8,0xa9,0xaa,0xb2,0xb3,0xb4, + 0xb5,0xb6,0xb7,0xb8,0xb9,0xba,0xc2,0xc3,0xc4,0xc5,0xc6,0xc7,0xc8,0xc9,0xca,0xd2,0xd3,0xd4,0xd5,0xd6,0xd7,0xd8,0xd9,0xda, + 0xe2,0xe3,0xe4,0xe5,0xe6,0xe7,0xe8,0xe9,0xea,0xf2,0xf3,0xf4,0xf5,0xf6,0xf7,0xf8,0xf9,0xfa + }; + // Huffman tables + static const unsigned short YDC_HT[256][2] = { {0,2},{2,3},{3,3},{4,3},{5,3},{6,3},{14,4},{30,5},{62,6},{126,7},{254,8},{510,9}}; + static const unsigned short UVDC_HT[256][2] = { {0,2},{1,2},{2,2},{6,3},{14,4},{30,5},{62,6},{126,7},{254,8},{510,9},{1022,10},{2046,11}}; + static const unsigned short YAC_HT[256][2] = { + {10,4},{0,2},{1,2},{4,3},{11,4},{26,5},{120,7},{248,8},{1014,10},{65410,16},{65411,16},{0,0},{0,0},{0,0},{0,0},{0,0},{0,0}, + {12,4},{27,5},{121,7},{502,9},{2038,11},{65412,16},{65413,16},{65414,16},{65415,16},{65416,16},{0,0},{0,0},{0,0},{0,0},{0,0},{0,0}, + {28,5},{249,8},{1015,10},{4084,12},{65417,16},{65418,16},{65419,16},{65420,16},{65421,16},{65422,16},{0,0},{0,0},{0,0},{0,0},{0,0},{0,0}, + {58,6},{503,9},{4085,12},{65423,16},{65424,16},{65425,16},{65426,16},{65427,16},{65428,16},{65429,16},{0,0},{0,0},{0,0},{0,0},{0,0},{0,0}, + {59,6},{1016,10},{65430,16},{65431,16},{65432,16},{65433,16},{65434,16},{65435,16},{65436,16},{65437,16},{0,0},{0,0},{0,0},{0,0},{0,0},{0,0}, + {122,7},{2039,11},{65438,16},{65439,16},{65440,16},{65441,16},{65442,16},{65443,16},{65444,16},{65445,16},{0,0},{0,0},{0,0},{0,0},{0,0},{0,0}, + {123,7},{4086,12},{65446,16},{65447,16},{65448,16},{65449,16},{65450,16},{65451,16},{65452,16},{65453,16},{0,0},{0,0},{0,0},{0,0},{0,0},{0,0}, + {250,8},{4087,12},{65454,16},{65455,16},{65456,16},{65457,16},{65458,16},{65459,16},{65460,16},{65461,16},{0,0},{0,0},{0,0},{0,0},{0,0},{0,0}, + {504,9},{32704,15},{65462,16},{65463,16},{65464,16},{65465,16},{65466,16},{65467,16},{65468,16},{65469,16},{0,0},{0,0},{0,0},{0,0},{0,0},{0,0}, + {505,9},{65470,16},{65471,16},{65472,16},{65473,16},{65474,16},{65475,16},{65476,16},{65477,16},{65478,16},{0,0},{0,0},{0,0},{0,0},{0,0},{0,0}, + {506,9},{65479,16},{65480,16},{65481,16},{65482,16},{65483,16},{65484,16},{65485,16},{65486,16},{65487,16},{0,0},{0,0},{0,0},{0,0},{0,0},{0,0}, + {1017,10},{65488,16},{65489,16},{65490,16},{65491,16},{65492,16},{65493,16},{65494,16},{65495,16},{65496,16},{0,0},{0,0},{0,0},{0,0},{0,0},{0,0}, + {1018,10},{65497,16},{65498,16},{65499,16},{65500,16},{65501,16},{65502,16},{65503,16},{65504,16},{65505,16},{0,0},{0,0},{0,0},{0,0},{0,0},{0,0}, + {2040,11},{65506,16},{65507,16},{65508,16},{65509,16},{65510,16},{65511,16},{65512,16},{65513,16},{65514,16},{0,0},{0,0},{0,0},{0,0},{0,0},{0,0}, + {65515,16},{65516,16},{65517,16},{65518,16},{65519,16},{65520,16},{65521,16},{65522,16},{65523,16},{65524,16},{0,0},{0,0},{0,0},{0,0},{0,0}, + {2041,11},{65525,16},{65526,16},{65527,16},{65528,16},{65529,16},{65530,16},{65531,16},{65532,16},{65533,16},{65534,16},{0,0},{0,0},{0,0},{0,0},{0,0} + }; + static const unsigned short UVAC_HT[256][2] = { + {0,2},{1,2},{4,3},{10,4},{24,5},{25,5},{56,6},{120,7},{500,9},{1014,10},{4084,12},{0,0},{0,0},{0,0},{0,0},{0,0},{0,0}, + {11,4},{57,6},{246,8},{501,9},{2038,11},{4085,12},{65416,16},{65417,16},{65418,16},{65419,16},{0,0},{0,0},{0,0},{0,0},{0,0},{0,0}, + {26,5},{247,8},{1015,10},{4086,12},{32706,15},{65420,16},{65421,16},{65422,16},{65423,16},{65424,16},{0,0},{0,0},{0,0},{0,0},{0,0},{0,0}, + {27,5},{248,8},{1016,10},{4087,12},{65425,16},{65426,16},{65427,16},{65428,16},{65429,16},{65430,16},{0,0},{0,0},{0,0},{0,0},{0,0},{0,0}, + {58,6},{502,9},{65431,16},{65432,16},{65433,16},{65434,16},{65435,16},{65436,16},{65437,16},{65438,16},{0,0},{0,0},{0,0},{0,0},{0,0},{0,0}, + {59,6},{1017,10},{65439,16},{65440,16},{65441,16},{65442,16},{65443,16},{65444,16},{65445,16},{65446,16},{0,0},{0,0},{0,0},{0,0},{0,0},{0,0}, + {121,7},{2039,11},{65447,16},{65448,16},{65449,16},{65450,16},{65451,16},{65452,16},{65453,16},{65454,16},{0,0},{0,0},{0,0},{0,0},{0,0},{0,0}, + {122,7},{2040,11},{65455,16},{65456,16},{65457,16},{65458,16},{65459,16},{65460,16},{65461,16},{65462,16},{0,0},{0,0},{0,0},{0,0},{0,0},{0,0}, + {249,8},{65463,16},{65464,16},{65465,16},{65466,16},{65467,16},{65468,16},{65469,16},{65470,16},{65471,16},{0,0},{0,0},{0,0},{0,0},{0,0},{0,0}, + {503,9},{65472,16},{65473,16},{65474,16},{65475,16},{65476,16},{65477,16},{65478,16},{65479,16},{65480,16},{0,0},{0,0},{0,0},{0,0},{0,0},{0,0}, + {504,9},{65481,16},{65482,16},{65483,16},{65484,16},{65485,16},{65486,16},{65487,16},{65488,16},{65489,16},{0,0},{0,0},{0,0},{0,0},{0,0},{0,0}, + {505,9},{65490,16},{65491,16},{65492,16},{65493,16},{65494,16},{65495,16},{65496,16},{65497,16},{65498,16},{0,0},{0,0},{0,0},{0,0},{0,0},{0,0}, + {506,9},{65499,16},{65500,16},{65501,16},{65502,16},{65503,16},{65504,16},{65505,16},{65506,16},{65507,16},{0,0},{0,0},{0,0},{0,0},{0,0},{0,0}, + {2041,11},{65508,16},{65509,16},{65510,16},{65511,16},{65512,16},{65513,16},{65514,16},{65515,16},{65516,16},{0,0},{0,0},{0,0},{0,0},{0,0},{0,0}, + {16352,14},{65517,16},{65518,16},{65519,16},{65520,16},{65521,16},{65522,16},{65523,16},{65524,16},{65525,16},{0,0},{0,0},{0,0},{0,0},{0,0}, + {1018,10},{32707,15},{65526,16},{65527,16},{65528,16},{65529,16},{65530,16},{65531,16},{65532,16},{65533,16},{65534,16},{0,0},{0,0},{0,0},{0,0},{0,0} + }; + static const int YQT[] = {16,11,10,16,24,40,51,61,12,12,14,19,26,58,60,55,14,13,16,24,40,57,69,56,14,17,22,29,51,87,80,62,18,22, + 37,56,68,109,103,77,24,35,55,64,81,104,113,92,49,64,78,87,103,121,120,101,72,92,95,98,112,100,103,99}; + static const int UVQT[] = {17,18,24,47,99,99,99,99,18,21,26,66,99,99,99,99,24,26,56,99,99,99,99,99,47,66,99,99,99,99,99,99, + 99,99,99,99,99,99,99,99,99,99,99,99,99,99,99,99,99,99,99,99,99,99,99,99,99,99,99,99,99,99,99,99}; + static const float aasf[] = { 1.0f * 2.828427125f, 1.387039845f * 2.828427125f, 1.306562965f * 2.828427125f, 1.175875602f * 2.828427125f, + 1.0f * 2.828427125f, 0.785694958f * 2.828427125f, 0.541196100f * 2.828427125f, 0.275899379f * 2.828427125f }; + + int row, col, i, k, subsample; + float fdtbl_Y[64], fdtbl_UV[64]; + unsigned char YTable[64], UVTable[64]; + + if(!data || !width || !height || comp > 4 || comp < 1) { + return 0; + } + + quality = quality ? quality : 90; + subsample = quality <= 90 ? 1 : 0; + quality = quality < 1 ? 1 : quality > 100 ? 100 : quality; + quality = quality < 50 ? 5000 / quality : 200 - quality * 2; + + for(i = 0; i < 64; ++i) { + int uvti, yti = (YQT[i]*quality+50)/100; + YTable[stbiw__jpg_ZigZag[i]] = (unsigned char) (yti < 1 ? 1 : yti > 255 ? 255 : yti); + uvti = (UVQT[i]*quality+50)/100; + UVTable[stbiw__jpg_ZigZag[i]] = (unsigned char) (uvti < 1 ? 1 : uvti > 255 ? 255 : uvti); + } + + for(row = 0, k = 0; row < 8; ++row) { + for(col = 0; col < 8; ++col, ++k) { + fdtbl_Y[k] = 1 / (YTable [stbiw__jpg_ZigZag[k]] * aasf[row] * aasf[col]); + fdtbl_UV[k] = 1 / (UVTable[stbiw__jpg_ZigZag[k]] * aasf[row] * aasf[col]); + } + } + + // Write Headers + { + static const unsigned char head0[] = { 0xFF,0xD8,0xFF,0xE0,0,0x10,'J','F','I','F',0,1,1,0,0,1,0,1,0,0,0xFF,0xDB,0,0x84,0 }; + static const unsigned char head2[] = { 0xFF,0xDA,0,0xC,3,1,0,2,0x11,3,0x11,0,0x3F,0 }; + const unsigned char head1[] = { 0xFF,0xC0,0,0x11,8,(unsigned char)(height>>8),STBIW_UCHAR(height),(unsigned char)(width>>8),STBIW_UCHAR(width), + 3,1,(unsigned char)(subsample?0x22:0x11),0,2,0x11,1,3,0x11,1,0xFF,0xC4,0x01,0xA2,0 }; + s->func(s->context, (void*)head0, sizeof(head0)); + s->func(s->context, (void*)YTable, sizeof(YTable)); + stbiw__putc(s, 1); + s->func(s->context, UVTable, sizeof(UVTable)); + s->func(s->context, (void*)head1, sizeof(head1)); + s->func(s->context, (void*)(std_dc_luminance_nrcodes+1), sizeof(std_dc_luminance_nrcodes)-1); + s->func(s->context, (void*)std_dc_luminance_values, sizeof(std_dc_luminance_values)); + stbiw__putc(s, 0x10); // HTYACinfo + s->func(s->context, (void*)(std_ac_luminance_nrcodes+1), sizeof(std_ac_luminance_nrcodes)-1); + s->func(s->context, (void*)std_ac_luminance_values, sizeof(std_ac_luminance_values)); + stbiw__putc(s, 1); // HTUDCinfo + s->func(s->context, (void*)(std_dc_chrominance_nrcodes+1), sizeof(std_dc_chrominance_nrcodes)-1); + s->func(s->context, (void*)std_dc_chrominance_values, sizeof(std_dc_chrominance_values)); + stbiw__putc(s, 0x11); // HTUACinfo + s->func(s->context, (void*)(std_ac_chrominance_nrcodes+1), sizeof(std_ac_chrominance_nrcodes)-1); + s->func(s->context, (void*)std_ac_chrominance_values, sizeof(std_ac_chrominance_values)); + s->func(s->context, (void*)head2, sizeof(head2)); + } + + // Encode 8x8 macroblocks + { + static const unsigned short fillBits[] = {0x7F, 7}; + int DCY=0, DCU=0, DCV=0; + int bitBuf=0, bitCnt=0; + // comp == 2 is grey+alpha (alpha is ignored) + int ofsG = comp > 2 ? 1 : 0, ofsB = comp > 2 ? 2 : 0; + const unsigned char *dataR = (const unsigned char *)data; + const unsigned char *dataG = dataR + ofsG; + const unsigned char *dataB = dataR + ofsB; + int x, y, pos; + if(subsample) { + for(y = 0; y < height; y += 16) { + for(x = 0; x < width; x += 16) { + float Y[256], U[256], V[256]; + for(row = y, pos = 0; row < y+16; ++row) { + // row >= height => use last input row + int clamped_row = (row < height) ? row : height - 1; + int base_p = (stbi__flip_vertically_on_write ? (height-1-clamped_row) : clamped_row)*width*comp; + for(col = x; col < x+16; ++col, ++pos) { + // if col >= width => use pixel from last input column + int p = base_p + ((col < width) ? col : (width-1))*comp; + float r = dataR[p], g = dataG[p], b = dataB[p]; + Y[pos]= +0.29900f*r + 0.58700f*g + 0.11400f*b - 128; + U[pos]= -0.16874f*r - 0.33126f*g + 0.50000f*b; + V[pos]= +0.50000f*r - 0.41869f*g - 0.08131f*b; + } + } + DCY = stbiw__jpg_processDU(s, &bitBuf, &bitCnt, Y+0, 16, fdtbl_Y, DCY, YDC_HT, YAC_HT); + DCY = stbiw__jpg_processDU(s, &bitBuf, &bitCnt, Y+8, 16, fdtbl_Y, DCY, YDC_HT, YAC_HT); + DCY = stbiw__jpg_processDU(s, &bitBuf, &bitCnt, Y+128, 16, fdtbl_Y, DCY, YDC_HT, YAC_HT); + DCY = stbiw__jpg_processDU(s, &bitBuf, &bitCnt, Y+136, 16, fdtbl_Y, DCY, YDC_HT, YAC_HT); + + // subsample U,V + { + float subU[64], subV[64]; + int yy, xx; + for(yy = 0, pos = 0; yy < 8; ++yy) { + for(xx = 0; xx < 8; ++xx, ++pos) { + int j = yy*32+xx*2; + subU[pos] = (U[j+0] + U[j+1] + U[j+16] + U[j+17]) * 0.25f; + subV[pos] = (V[j+0] + V[j+1] + V[j+16] + V[j+17]) * 0.25f; + } + } + DCU = stbiw__jpg_processDU(s, &bitBuf, &bitCnt, subU, 8, fdtbl_UV, DCU, UVDC_HT, UVAC_HT); + DCV = stbiw__jpg_processDU(s, &bitBuf, &bitCnt, subV, 8, fdtbl_UV, DCV, UVDC_HT, UVAC_HT); + } + } + } + } else { + for(y = 0; y < height; y += 8) { + for(x = 0; x < width; x += 8) { + float Y[64], U[64], V[64]; + for(row = y, pos = 0; row < y+8; ++row) { + // row >= height => use last input row + int clamped_row = (row < height) ? row : height - 1; + int base_p = (stbi__flip_vertically_on_write ? (height-1-clamped_row) : clamped_row)*width*comp; + for(col = x; col < x+8; ++col, ++pos) { + // if col >= width => use pixel from last input column + int p = base_p + ((col < width) ? col : (width-1))*comp; + float r = dataR[p], g = dataG[p], b = dataB[p]; + Y[pos]= +0.29900f*r + 0.58700f*g + 0.11400f*b - 128; + U[pos]= -0.16874f*r - 0.33126f*g + 0.50000f*b; + V[pos]= +0.50000f*r - 0.41869f*g - 0.08131f*b; + } + } + + DCY = stbiw__jpg_processDU(s, &bitBuf, &bitCnt, Y, 8, fdtbl_Y, DCY, YDC_HT, YAC_HT); + DCU = stbiw__jpg_processDU(s, &bitBuf, &bitCnt, U, 8, fdtbl_UV, DCU, UVDC_HT, UVAC_HT); + DCV = stbiw__jpg_processDU(s, &bitBuf, &bitCnt, V, 8, fdtbl_UV, DCV, UVDC_HT, UVAC_HT); + } + } + } + + // Do the bit alignment of the EOI marker + stbiw__jpg_writeBits(s, &bitBuf, &bitCnt, fillBits); + } + + // EOI + stbiw__putc(s, 0xFF); + stbiw__putc(s, 0xD9); + + return 1; +} + +STBIWDEF int stbi_write_jpg_to_func(stbi_write_func *func, void *context, int x, int y, int comp, const void *data, int quality) +{ + stbi__write_context s; + stbi__start_write_callbacks(&s, func, context); + return stbi_write_jpg_core(&s, x, y, comp, (void *) data, quality); +} + + +#ifndef STBI_WRITE_NO_STDIO +STBIWDEF int stbi_write_jpg(char const *filename, int x, int y, int comp, const void *data, int quality) +{ + stbi__write_context s; + if (stbi__start_write_file(&s,filename)) { + int r = stbi_write_jpg_core(&s, x, y, comp, data, quality); + stbi__end_write_file(&s); + return r; + } else + return 0; +} +#endif + +#endif // STB_IMAGE_WRITE_IMPLEMENTATION + +/* Revision history + 1.14 (2020-02-02) updated JPEG writer to downsample chroma channels + 1.13 + 1.12 + 1.11 (2019-08-11) + + 1.10 (2019-02-07) + support utf8 filenames in Windows; fix warnings and platform ifdefs + 1.09 (2018-02-11) + fix typo in zlib quality API, improve STB_I_W_STATIC in C++ + 1.08 (2018-01-29) + add stbi__flip_vertically_on_write, external zlib, zlib quality, choose PNG filter + 1.07 (2017-07-24) + doc fix + 1.06 (2017-07-23) + writing JPEG (using Jon Olick's code) + 1.05 ??? + 1.04 (2017-03-03) + monochrome BMP expansion + 1.03 ??? + 1.02 (2016-04-02) + avoid allocating large structures on the stack + 1.01 (2016-01-16) + STBIW_REALLOC_SIZED: support allocators with no realloc support + avoid race-condition in crc initialization + minor compile issues + 1.00 (2015-09-14) + installable file IO function + 0.99 (2015-09-13) + warning fixes; TGA rle support + 0.98 (2015-04-08) + added STBIW_MALLOC, STBIW_ASSERT etc + 0.97 (2015-01-18) + fixed HDR asserts, rewrote HDR rle logic + 0.96 (2015-01-17) + add HDR output + fix monochrome BMP + 0.95 (2014-08-17) + add monochrome TGA output + 0.94 (2014-05-31) + rename private functions to avoid conflicts with stb_image.h + 0.93 (2014-05-27) + warning fixes + 0.92 (2010-08-01) + casts to unsigned char to fix warnings + 0.91 (2010-07-17) + first public release + 0.90 first internal release +*/ + +/* +------------------------------------------------------------------------------ +This software is available under 2 licenses -- choose whichever you prefer. +------------------------------------------------------------------------------ +ALTERNATIVE A - MIT License +Copyright (c) 2017 Sean Barrett +Permission is hereby granted, free of charge, to any person obtaining a copy of +this software and associated documentation files (the "Software"), to deal in +the Software without restriction, including without limitation the rights to +use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies +of the Software, and to permit persons to whom the Software is furnished to do +so, subject to the following conditions: +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +SOFTWARE. +------------------------------------------------------------------------------ +ALTERNATIVE B - Public Domain (www.unlicense.org) +This is free and unencumbered software released into the public domain. +Anyone is free to copy, modify, publish, use, compile, sell, or distribute this +software, either in source code form or as a compiled binary, for any purpose, +commercial or non-commercial, and by any means. +In jurisdictions that recognize copyright laws, the author or authors of this +software dedicate any and all copyright interest in the software to the public +domain. We make this dedication for the benefit of the public at large and to +the detriment of our heirs and successors. We intend this dedication to be an +overt act of relinquishment in perpetuity of all present and future rights to +this software under copyright law. +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN +ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION +WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. +------------------------------------------------------------------------------ +*/ diff --git a/libs/unimrcp/libs/mpf/mpf.2017.vcxproj b/libs/unimrcp/libs/mpf/mpf.2017.vcxproj index 578280ea27..4cd900b2df 100644 --- a/libs/unimrcp/libs/mpf/mpf.2017.vcxproj +++ b/libs/unimrcp/libs/mpf/mpf.2017.vcxproj @@ -1,196 +1,201 @@ - - - - - Debug - Win32 - - - Debug - x64 - - - Release - Win32 - - - Release - x64 - - - - mpf - {B5A00BFA-6083-4FAE-A097-71642D6473B5} - mpf - Win32Proj - - - - StaticLibrary - Unicode - true - $(DefaultPlatformToolset) - - - StaticLibrary - Unicode - $(DefaultPlatformToolset) - - - StaticLibrary - Unicode - true - $(DefaultPlatformToolset) - - - StaticLibrary - Unicode - $(DefaultPlatformToolset) - - - - - - - - - - - - - - - - - - - - - - - - - - - <_ProjectFileVersion>10.0.30319.1 - $(PlatformName)\$(Configuration)\ - $(PlatformName)\$(Configuration)\ - $(PlatformName)\$(Configuration)\ - $(PlatformName)\$(Configuration)\ - $(PlatformName)\$(Configuration)\ - $(PlatformName)\$(Configuration)\ - $(SolutionDir)$(PlatformName)\$(Configuration)\ - $(PlatformName)\$(Configuration)\ - - - - codecs;%(AdditionalIncludeDirectories) - APT_STATIC_LIB;MPF_STATIC_LIB;%(PreprocessorDefinitions) - - - - - X64 - - - codecs;%(AdditionalIncludeDirectories) - APT_STATIC_LIB;MPF_STATIC_LIB;%(PreprocessorDefinitions) - false - ProgramDatabase - - - - - codecs;%(AdditionalIncludeDirectories) - APT_STATIC_LIB;MPF_STATIC_LIB;%(PreprocessorDefinitions) - - - - - X64 - - - codecs;%(AdditionalIncludeDirectories) - APT_STATIC_LIB;MPF_STATIC_LIB;%(PreprocessorDefinitions) - false - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - + + + + + Debug + Win32 + + + Debug + x64 + + + Release + Win32 + + + Release + x64 + + + + mpf + {B5A00BFA-6083-4FAE-A097-71642D6473B5} + mpf + Win32Proj + + + + StaticLibrary + Unicode + true + $(DefaultPlatformToolset) + + + StaticLibrary + Unicode + $(DefaultPlatformToolset) + + + StaticLibrary + Unicode + true + $(DefaultPlatformToolset) + + + StaticLibrary + Unicode + $(DefaultPlatformToolset) + + + + + + + + + + + + + + + + + + + + + + + + + + + <_ProjectFileVersion>10.0.30319.1 + $(PlatformName)\$(Configuration)\ + $(PlatformName)\$(Configuration)\ + $(PlatformName)\$(Configuration)\ + $(PlatformName)\$(Configuration)\ + $(PlatformName)\$(Configuration)\ + $(PlatformName)\$(Configuration)\ + $(SolutionDir)$(PlatformName)\$(Configuration)\ + $(PlatformName)\$(Configuration)\ + + + + codecs;%(AdditionalIncludeDirectories) + APT_STATIC_LIB;MPF_STATIC_LIB;%(PreprocessorDefinitions) + + + + + X64 + + + codecs;%(AdditionalIncludeDirectories) + APT_STATIC_LIB;MPF_STATIC_LIB;%(PreprocessorDefinitions) + false + ProgramDatabase + + + + + codecs;%(AdditionalIncludeDirectories) + APT_STATIC_LIB;MPF_STATIC_LIB;%(PreprocessorDefinitions) + + + + + X64 + + + codecs;%(AdditionalIncludeDirectories) + APT_STATIC_LIB;MPF_STATIC_LIB;%(PreprocessorDefinitions) + false + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + {f6c55d93-b927-4483-bb69-15aef3dd2dff} + + + + + \ No newline at end of file diff --git a/libs/unimrcp/libs/mrcp-client/mrcpclient.2017.vcxproj b/libs/unimrcp/libs/mrcp-client/mrcpclient.2017.vcxproj index d00e3d66dc..e5cfaa0b33 100644 --- a/libs/unimrcp/libs/mrcp-client/mrcpclient.2017.vcxproj +++ b/libs/unimrcp/libs/mrcp-client/mrcpclient.2017.vcxproj @@ -1,126 +1,131 @@ - - - - - Debug - Win32 - - - Debug - x64 - - - Release - Win32 - - - Release - x64 - - - - mrcpclient - {72782932-37CC-46AE-8C7F-9A7B1A6EE108} - mrcpclient - Win32Proj - - - - StaticLibrary - Unicode - true - $(DefaultPlatformToolset) - - - StaticLibrary - Unicode - $(DefaultPlatformToolset) - - - StaticLibrary - Unicode - true - $(DefaultPlatformToolset) - - - StaticLibrary - Unicode - $(DefaultPlatformToolset) - - - - - - - - - - - - - - - - - - - - - - - - - - - <_ProjectFileVersion>10.0.30319.1 - $(PlatformName)\$(Configuration)\ - $(PlatformName)\$(Configuration)\ - $(SolutionDir)$(PlatformName)\$(Configuration)\ - $(PlatformName)\$(Configuration)\ - $(PlatformName)\$(Configuration)\ - $(PlatformName)\$(Configuration)\ - $(SolutionDir)$(PlatformName)\$(Configuration)\ - $(PlatformName)\$(Configuration)\ - - - - APT_STATIC_LIB;MPF_STATIC_LIB;MRCP_STATIC_LIB;%(PreprocessorDefinitions) - - - - - X64 - - - APT_STATIC_LIB;MPF_STATIC_LIB;MRCP_STATIC_LIB;%(PreprocessorDefinitions) - ProgramDatabase - - - - - APT_STATIC_LIB;MPF_STATIC_LIB;MRCP_STATIC_LIB;%(PreprocessorDefinitions) - - - - - X64 - - - APT_STATIC_LIB;MPF_STATIC_LIB;MRCP_STATIC_LIB;%(PreprocessorDefinitions) - - - - - - - - - - - - - - - - + + + + + Debug + Win32 + + + Debug + x64 + + + Release + Win32 + + + Release + x64 + + + + mrcpclient + {72782932-37CC-46AE-8C7F-9A7B1A6EE108} + mrcpclient + Win32Proj + + + + StaticLibrary + Unicode + true + $(DefaultPlatformToolset) + + + StaticLibrary + Unicode + $(DefaultPlatformToolset) + + + StaticLibrary + Unicode + true + $(DefaultPlatformToolset) + + + StaticLibrary + Unicode + $(DefaultPlatformToolset) + + + + + + + + + + + + + + + + + + + + + + + + + + + <_ProjectFileVersion>10.0.30319.1 + $(PlatformName)\$(Configuration)\ + $(PlatformName)\$(Configuration)\ + $(SolutionDir)$(PlatformName)\$(Configuration)\ + $(PlatformName)\$(Configuration)\ + $(PlatformName)\$(Configuration)\ + $(PlatformName)\$(Configuration)\ + $(SolutionDir)$(PlatformName)\$(Configuration)\ + $(PlatformName)\$(Configuration)\ + + + + APT_STATIC_LIB;MPF_STATIC_LIB;MRCP_STATIC_LIB;%(PreprocessorDefinitions) + + + + + X64 + + + APT_STATIC_LIB;MPF_STATIC_LIB;MRCP_STATIC_LIB;%(PreprocessorDefinitions) + ProgramDatabase + + + + + APT_STATIC_LIB;MPF_STATIC_LIB;MRCP_STATIC_LIB;%(PreprocessorDefinitions) + + + + + X64 + + + APT_STATIC_LIB;MPF_STATIC_LIB;MRCP_STATIC_LIB;%(PreprocessorDefinitions) + + + + + + + + + + + + + + + + {f6c55d93-b927-4483-bb69-15aef3dd2dff} + + + + + \ No newline at end of file diff --git a/libs/unimrcp/libs/mrcp-signaling/mrcpsignaling.2017.vcxproj b/libs/unimrcp/libs/mrcp-signaling/mrcpsignaling.2017.vcxproj index 8325ee4df4..d8f8525d72 100644 --- a/libs/unimrcp/libs/mrcp-signaling/mrcpsignaling.2017.vcxproj +++ b/libs/unimrcp/libs/mrcp-signaling/mrcpsignaling.2017.vcxproj @@ -1,125 +1,130 @@ - - - - - Debug - Win32 - - - Debug - x64 - - - Release - Win32 - - - Release - x64 - - - - mrcpsignaling - {12A49562-BAB9-43A3-A21D-15B60BBB4C31} - mrcpsignaling - Win32Proj - - - - StaticLibrary - Unicode - true - $(DefaultPlatformToolset) - - - StaticLibrary - Unicode - $(DefaultPlatformToolset) - - - StaticLibrary - Unicode - true - $(DefaultPlatformToolset) - - - StaticLibrary - Unicode - $(DefaultPlatformToolset) - - - - - - - - - - - - - - - - - - - - - - - - - - - <_ProjectFileVersion>10.0.30319.1 - $(PlatformName)\$(Configuration)\ - $(PlatformName)\$(Configuration)\ - $(SolutionDir)$(PlatformName)\$(Configuration)\ - $(PlatformName)\$(Configuration)\ - $(PlatformName)\$(Configuration)\ - $(PlatformName)\$(Configuration)\ - $(SolutionDir)$(PlatformName)\$(Configuration)\ - $(PlatformName)\$(Configuration)\ - - - - APT_STATIC_LIB;MPF_STATIC_LIB;MRCP_STATIC_LIB;%(PreprocessorDefinitions) - - - - - X64 - - - APT_STATIC_LIB;MPF_STATIC_LIB;MRCP_STATIC_LIB;%(PreprocessorDefinitions) - ProgramDatabase - - - - - APT_STATIC_LIB;MPF_STATIC_LIB;MRCP_STATIC_LIB;%(PreprocessorDefinitions) - - - - - X64 - - - APT_STATIC_LIB;MPF_STATIC_LIB;MRCP_STATIC_LIB;%(PreprocessorDefinitions) - - - - - - - - - - - - - - - + + + + + Debug + Win32 + + + Debug + x64 + + + Release + Win32 + + + Release + x64 + + + + mrcpsignaling + {12A49562-BAB9-43A3-A21D-15B60BBB4C31} + mrcpsignaling + Win32Proj + + + + StaticLibrary + Unicode + true + $(DefaultPlatformToolset) + + + StaticLibrary + Unicode + $(DefaultPlatformToolset) + + + StaticLibrary + Unicode + true + $(DefaultPlatformToolset) + + + StaticLibrary + Unicode + $(DefaultPlatformToolset) + + + + + + + + + + + + + + + + + + + + + + + + + + + <_ProjectFileVersion>10.0.30319.1 + $(PlatformName)\$(Configuration)\ + $(PlatformName)\$(Configuration)\ + $(SolutionDir)$(PlatformName)\$(Configuration)\ + $(PlatformName)\$(Configuration)\ + $(PlatformName)\$(Configuration)\ + $(PlatformName)\$(Configuration)\ + $(SolutionDir)$(PlatformName)\$(Configuration)\ + $(PlatformName)\$(Configuration)\ + + + + APT_STATIC_LIB;MPF_STATIC_LIB;MRCP_STATIC_LIB;%(PreprocessorDefinitions) + + + + + X64 + + + APT_STATIC_LIB;MPF_STATIC_LIB;MRCP_STATIC_LIB;%(PreprocessorDefinitions) + ProgramDatabase + + + + + APT_STATIC_LIB;MPF_STATIC_LIB;MRCP_STATIC_LIB;%(PreprocessorDefinitions) + + + + + X64 + + + APT_STATIC_LIB;MPF_STATIC_LIB;MRCP_STATIC_LIB;%(PreprocessorDefinitions) + + + + + + + + + + + + + + + {f6c55d93-b927-4483-bb69-15aef3dd2dff} + + + + + \ No newline at end of file diff --git a/libs/unimrcp/libs/mrcp/mrcp.2017.vcxproj b/libs/unimrcp/libs/mrcp/mrcp.2017.vcxproj index 0e1d64d533..d2420fde7c 100644 --- a/libs/unimrcp/libs/mrcp/mrcp.2017.vcxproj +++ b/libs/unimrcp/libs/mrcp/mrcp.2017.vcxproj @@ -1,158 +1,163 @@ - - - - - Debug - Win32 - - - Debug - x64 - - - Release - Win32 - - - Release - x64 - - - - mrcp - {1C320193-46A6-4B34-9C56-8AB584FC1B56} - mrcp - Win32Proj - - - - StaticLibrary - Unicode - true - $(DefaultPlatformToolset) - - - StaticLibrary - Unicode - $(DefaultPlatformToolset) - - - StaticLibrary - Unicode - true - $(DefaultPlatformToolset) - - - StaticLibrary - Unicode - $(DefaultPlatformToolset) - - - - - - - - - - - - - - - - - - - - - - - - - - - <_ProjectFileVersion>10.0.30319.1 - $(PlatformName)\$(Configuration)\ - $(PlatformName)\$(Configuration)\ - $(PlatformName)\$(Configuration)\ - $(PlatformName)\$(Configuration)\ - $(PlatformName)\$(Configuration)\ - $(PlatformName)\$(Configuration)\ - $(SolutionDir)$(PlatformName)\$(Configuration)\ - $(PlatformName)\$(Configuration)\ - - - - %(AdditionalIncludeDirectories) - APT_STATIC_LIB;MPF_STATIC_LIB;MRCP_STATIC_LIB;%(PreprocessorDefinitions) - - - - - X64 - - - %(AdditionalIncludeDirectories) - APT_STATIC_LIB;MPF_STATIC_LIB;MRCP_STATIC_LIB;%(PreprocessorDefinitions) - ProgramDatabase - - - - - %(AdditionalIncludeDirectories) - APT_STATIC_LIB;MPF_STATIC_LIB;MRCP_STATIC_LIB;%(PreprocessorDefinitions) - - - - - X64 - - - %(AdditionalIncludeDirectories) - APT_STATIC_LIB;MPF_STATIC_LIB;MRCP_STATIC_LIB;%(PreprocessorDefinitions) - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - + + + + + Debug + Win32 + + + Debug + x64 + + + Release + Win32 + + + Release + x64 + + + + mrcp + {1C320193-46A6-4B34-9C56-8AB584FC1B56} + mrcp + Win32Proj + + + + StaticLibrary + Unicode + true + $(DefaultPlatformToolset) + + + StaticLibrary + Unicode + $(DefaultPlatformToolset) + + + StaticLibrary + Unicode + true + $(DefaultPlatformToolset) + + + StaticLibrary + Unicode + $(DefaultPlatformToolset) + + + + + + + + + + + + + + + + + + + + + + + + + + + <_ProjectFileVersion>10.0.30319.1 + $(PlatformName)\$(Configuration)\ + $(PlatformName)\$(Configuration)\ + $(PlatformName)\$(Configuration)\ + $(PlatformName)\$(Configuration)\ + $(PlatformName)\$(Configuration)\ + $(PlatformName)\$(Configuration)\ + $(SolutionDir)$(PlatformName)\$(Configuration)\ + $(PlatformName)\$(Configuration)\ + + + + %(AdditionalIncludeDirectories) + APT_STATIC_LIB;MPF_STATIC_LIB;MRCP_STATIC_LIB;%(PreprocessorDefinitions) + + + + + X64 + + + %(AdditionalIncludeDirectories) + APT_STATIC_LIB;MPF_STATIC_LIB;MRCP_STATIC_LIB;%(PreprocessorDefinitions) + ProgramDatabase + + + + + %(AdditionalIncludeDirectories) + APT_STATIC_LIB;MPF_STATIC_LIB;MRCP_STATIC_LIB;%(PreprocessorDefinitions) + + + + + X64 + + + %(AdditionalIncludeDirectories) + APT_STATIC_LIB;MPF_STATIC_LIB;MRCP_STATIC_LIB;%(PreprocessorDefinitions) + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + {f6c55d93-b927-4483-bb69-15aef3dd2dff} + + + + + \ No newline at end of file diff --git a/libs/unimrcp/libs/mrcpv2-transport/mrcpv2transport.2017.vcxproj b/libs/unimrcp/libs/mrcpv2-transport/mrcpv2transport.2017.vcxproj index a694094969..40a20105bf 100644 --- a/libs/unimrcp/libs/mrcpv2-transport/mrcpv2transport.2017.vcxproj +++ b/libs/unimrcp/libs/mrcpv2-transport/mrcpv2transport.2017.vcxproj @@ -1,129 +1,134 @@ - - - - - Debug - Win32 - - - Debug - x64 - - - Release - Win32 - - - Release - x64 - - - - mrcpv2transport - {A9EDAC04-6A5F-4BA7-BC0D-CCE7B255B6EA} - mrcpv2transport - Win32Proj - - - - StaticLibrary - Unicode - true - $(DefaultPlatformToolset) - - - StaticLibrary - Unicode - $(DefaultPlatformToolset) - - - StaticLibrary - Unicode - true - $(DefaultPlatformToolset) - - - StaticLibrary - Unicode - $(DefaultPlatformToolset) - - - - - - - - - - - - - - - - - - - - - - - - - - - <_ProjectFileVersion>10.0.30319.1 - $(PlatformName)\$(Configuration)\ - $(PlatformName)\$(Configuration)\ - $(SolutionDir)$(PlatformName)\$(Configuration)\ - $(PlatformName)\$(Configuration)\ - $(PlatformName)\$(Configuration)\ - $(PlatformName)\$(Configuration)\ - $(SolutionDir)$(PlatformName)\$(Configuration)\ - $(PlatformName)\$(Configuration)\ - - - - APT_STATIC_LIB;MPF_STATIC_LIB;MRCP_STATIC_LIB;%(PreprocessorDefinitions) - - - - - X64 - - - APT_STATIC_LIB;MPF_STATIC_LIB;MRCP_STATIC_LIB;%(PreprocessorDefinitions) - ProgramDatabase - - - - - APT_STATIC_LIB;MPF_STATIC_LIB;MRCP_STATIC_LIB;%(PreprocessorDefinitions) - - - - - X64 - - - APT_STATIC_LIB;MPF_STATIC_LIB;MRCP_STATIC_LIB;%(PreprocessorDefinitions) - - - - - - - - - - - - - - - - - - - + + + + + Debug + Win32 + + + Debug + x64 + + + Release + Win32 + + + Release + x64 + + + + mrcpv2transport + {A9EDAC04-6A5F-4BA7-BC0D-CCE7B255B6EA} + mrcpv2transport + Win32Proj + + + + StaticLibrary + Unicode + true + $(DefaultPlatformToolset) + + + StaticLibrary + Unicode + $(DefaultPlatformToolset) + + + StaticLibrary + Unicode + true + $(DefaultPlatformToolset) + + + StaticLibrary + Unicode + $(DefaultPlatformToolset) + + + + + + + + + + + + + + + + + + + + + + + + + + + <_ProjectFileVersion>10.0.30319.1 + $(PlatformName)\$(Configuration)\ + $(PlatformName)\$(Configuration)\ + $(SolutionDir)$(PlatformName)\$(Configuration)\ + $(PlatformName)\$(Configuration)\ + $(PlatformName)\$(Configuration)\ + $(PlatformName)\$(Configuration)\ + $(SolutionDir)$(PlatformName)\$(Configuration)\ + $(PlatformName)\$(Configuration)\ + + + + APT_STATIC_LIB;MPF_STATIC_LIB;MRCP_STATIC_LIB;%(PreprocessorDefinitions) + + + + + X64 + + + APT_STATIC_LIB;MPF_STATIC_LIB;MRCP_STATIC_LIB;%(PreprocessorDefinitions) + ProgramDatabase + + + + + APT_STATIC_LIB;MPF_STATIC_LIB;MRCP_STATIC_LIB;%(PreprocessorDefinitions) + + + + + X64 + + + APT_STATIC_LIB;MPF_STATIC_LIB;MRCP_STATIC_LIB;%(PreprocessorDefinitions) + + + + + + + + + + + + + + + + + + + {f6c55d93-b927-4483-bb69-15aef3dd2dff} + + + + + \ No newline at end of file diff --git a/libs/unimrcp/libs/uni-rtsp/unirtsp.2017.vcxproj b/libs/unimrcp/libs/uni-rtsp/unirtsp.2017.vcxproj index 1ae73fcb7f..1b368a09e6 100644 --- a/libs/unimrcp/libs/uni-rtsp/unirtsp.2017.vcxproj +++ b/libs/unimrcp/libs/uni-rtsp/unirtsp.2017.vcxproj @@ -1,136 +1,141 @@ - - - - - Debug - Win32 - - - Debug - x64 - - - Release - Win32 - - - Release - x64 - - - - unirtsp - {504B3154-7A4F-459D-9877-B951021C3F1F} - unirtsp - Win32Proj - - - - StaticLibrary - Unicode - true - $(DefaultPlatformToolset) - - - StaticLibrary - Unicode - $(DefaultPlatformToolset) - - - StaticLibrary - Unicode - true - $(DefaultPlatformToolset) - - - StaticLibrary - Unicode - $(DefaultPlatformToolset) - - - - - - - - - - - - - - - - - - - - - - - - - - - <_ProjectFileVersion>10.0.30319.1 - $(PlatformName)\$(Configuration)\ - $(PlatformName)\$(Configuration)\ - $(SolutionDir)$(PlatformName)\$(Configuration)\ - $(PlatformName)\$(Configuration)\ - $(PlatformName)\$(Configuration)\ - $(PlatformName)\$(Configuration)\ - $(SolutionDir)$(PlatformName)\$(Configuration)\ - $(PlatformName)\$(Configuration)\ - - - - codecs;%(AdditionalIncludeDirectories) - APT_STATIC_LIB;%(PreprocessorDefinitions) - - - - - X64 - - - codecs;%(AdditionalIncludeDirectories) - APT_STATIC_LIB;%(PreprocessorDefinitions) - ProgramDatabase - - - - - codecs;%(AdditionalIncludeDirectories) - APT_STATIC_LIB;%(PreprocessorDefinitions) - - - - - X64 - - - codecs;%(AdditionalIncludeDirectories) - APT_STATIC_LIB;%(PreprocessorDefinitions) - - - - - - - - - - - - - - - - - - - - - - + + + + + Debug + Win32 + + + Debug + x64 + + + Release + Win32 + + + Release + x64 + + + + unirtsp + {504B3154-7A4F-459D-9877-B951021C3F1F} + unirtsp + Win32Proj + + + + StaticLibrary + Unicode + true + $(DefaultPlatformToolset) + + + StaticLibrary + Unicode + $(DefaultPlatformToolset) + + + StaticLibrary + Unicode + true + $(DefaultPlatformToolset) + + + StaticLibrary + Unicode + $(DefaultPlatformToolset) + + + + + + + + + + + + + + + + + + + + + + + + + + + <_ProjectFileVersion>10.0.30319.1 + $(PlatformName)\$(Configuration)\ + $(PlatformName)\$(Configuration)\ + $(SolutionDir)$(PlatformName)\$(Configuration)\ + $(PlatformName)\$(Configuration)\ + $(PlatformName)\$(Configuration)\ + $(PlatformName)\$(Configuration)\ + $(SolutionDir)$(PlatformName)\$(Configuration)\ + $(PlatformName)\$(Configuration)\ + + + + codecs;%(AdditionalIncludeDirectories) + APT_STATIC_LIB;%(PreprocessorDefinitions) + + + + + X64 + + + codecs;%(AdditionalIncludeDirectories) + APT_STATIC_LIB;%(PreprocessorDefinitions) + ProgramDatabase + + + + + codecs;%(AdditionalIncludeDirectories) + APT_STATIC_LIB;%(PreprocessorDefinitions) + + + + + X64 + + + codecs;%(AdditionalIncludeDirectories) + APT_STATIC_LIB;%(PreprocessorDefinitions) + + + + + + + + + + + + + + + + + + + + + + {f6c55d93-b927-4483-bb69-15aef3dd2dff} + + + + + \ No newline at end of file diff --git a/libs/win32/libshout/libshout.2017.vcxproj b/libs/win32/libshout/libshout.2017.vcxproj index bf298a4238..c7790e7f0f 100644 --- a/libs/win32/libshout/libshout.2017.vcxproj +++ b/libs/win32/libshout/libshout.2017.vcxproj @@ -1,189 +1,192 @@ - - - - - Debug - Win32 - - - Debug - x64 - - - Release - Win32 - - - Release - x64 - - - - {D3D8B329-20BE-475E-9E83-653CEA0E0EF5} - libshout - libshout - - - - StaticLibrary - MultiByte - $(DefaultPlatformToolset) - - - StaticLibrary - MultiByte - $(DefaultPlatformToolset) - - - StaticLibrary - MultiByte - $(DefaultPlatformToolset) - - - StaticLibrary - MultiByte - $(DefaultPlatformToolset) - - - - - - - - - - - - - - - - - - - - - - - - <_ProjectFileVersion>10.0.30319.1 - - - - MaxSpeed - OnlyExplicitInline - .\;..\..\libshout-2.2.2\src;..\..\libshout-2.2.2\include;..\..\libogg-1.1.3\include;..\..\pthreads-w32-2-9-1;..\..\libshout-2.2.2\win32\include;%(AdditionalIncludeDirectories) - _TIMESPEC_DEFINED;WIN32;_LIB;_WIN32;VERSION="2.0.0";LIBSHOUT_MAJOR=2;LIBSHOUT_MINOR=0;LIBSHOUT_MICRO=0;HAVE_WINSOCK2_H;_CRT_SECURE_NO_DEPRECATE;_CRT_NONSTDC_NO_DEPRECATE;%(PreprocessorDefinitions) - true - MultiThreaded - true - TurnOffAllWarnings - true - - - NDEBUG;%(PreprocessorDefinitions) - 0x0409 - - - true - - - - - X64 - - - MaxSpeed - OnlyExplicitInline - .\;..\..\libshout-2.2.2\src;..\..\libshout-2.2.2\include;..\..\libogg-1.1.3\include;..\..\pthreads-w32-2-9-1;..\..\libshout-2.2.2\win32\include;%(AdditionalIncludeDirectories) - _TIMESPEC_DEFINED;WIN32;_LIB;_WIN32;VERSION="2.0.0";LIBSHOUT_MAJOR=2;LIBSHOUT_MINOR=0;LIBSHOUT_MICRO=0;HAVE_WINSOCK2_H;_CRT_SECURE_NO_DEPRECATE;_CRT_NONSTDC_NO_DEPRECATE;%(PreprocessorDefinitions) - true - MultiThreaded - true - TurnOffAllWarnings - true - - - NDEBUG;%(PreprocessorDefinitions) - 0x0409 - - - true - - - - - Disabled - .\;..\..\libshout-2.2.2\src;..\..\libshout-2.2.2\include;..\..\libogg-1.1.3\include;..\..\pthreads-w32-2-9-1;..\..\libshout-2.2.2\win32\include;%(AdditionalIncludeDirectories) - _TIMESPEC_DEFINED;WIN32;_DEBUG;_LIB;_WIN32;VERSION="2.0.0";LIBSHOUT_MAJOR=2;LIBSHOUT_MINOR=0;LIBSHOUT_MICRO=0;HAVE_WINSOCK2_H;_CRT_SECURE_NO_DEPRECATE;_CRT_NONSTDC_NO_DEPRECATE;%(PreprocessorDefinitions) - true - EnableFastChecks - MultiThreadedDebug - TurnOffAllWarnings - true - - - _DEBUG;%(PreprocessorDefinitions) - 0x0409 - - - true - - - - - X64 - - - Disabled - .\;..\..\libshout-2.2.2\src;..\..\libshout-2.2.2\include;..\..\libogg-1.1.3\include;..\..\pthreads-w32-2-9-1;..\..\libshout-2.2.2\win32\include;%(AdditionalIncludeDirectories) - _TIMESPEC_DEFINED;WIN32;_DEBUG;_LIB;_WIN32;VERSION="2.0.0";LIBSHOUT_MAJOR=2;LIBSHOUT_MINOR=0;LIBSHOUT_MICRO=0;HAVE_WINSOCK2_H;_CRT_SECURE_NO_DEPRECATE;_CRT_NONSTDC_NO_DEPRECATE;%(PreprocessorDefinitions) - true - EnableFastChecks - MultiThreadedDebug - TurnOffAllWarnings - true - - - _DEBUG;%(PreprocessorDefinitions) - 0x0409 - - - true - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - {0feeaec6-4399-4c46-b7db-62ece80d15b4} - false - - - - - + + + + + Debug + Win32 + + + Debug + x64 + + + Release + Win32 + + + Release + x64 + + + + {D3D8B329-20BE-475E-9E83-653CEA0E0EF5} + libshout + libshout + + + + StaticLibrary + MultiByte + $(DefaultPlatformToolset) + + + StaticLibrary + MultiByte + $(DefaultPlatformToolset) + + + StaticLibrary + MultiByte + $(DefaultPlatformToolset) + + + StaticLibrary + MultiByte + $(DefaultPlatformToolset) + + + + + + + + + + + + + + + + + + + + + + + + <_ProjectFileVersion>10.0.30319.1 + + + + MaxSpeed + OnlyExplicitInline + .\;..\..\libshout-2.2.2\src;..\..\libshout-2.2.2\include;..\..\libogg-1.1.3\include;..\..\pthreads-w32-2-9-1;..\..\libshout-2.2.2\win32\include;%(AdditionalIncludeDirectories) + _TIMESPEC_DEFINED;WIN32;_LIB;_WIN32;VERSION="2.0.0";LIBSHOUT_MAJOR=2;LIBSHOUT_MINOR=0;LIBSHOUT_MICRO=0;HAVE_WINSOCK2_H;_CRT_SECURE_NO_DEPRECATE;_CRT_NONSTDC_NO_DEPRECATE;%(PreprocessorDefinitions) + true + MultiThreaded + true + TurnOffAllWarnings + true + + + NDEBUG;%(PreprocessorDefinitions) + 0x0409 + + + true + + + + + X64 + + + MaxSpeed + OnlyExplicitInline + .\;..\..\libshout-2.2.2\src;..\..\libshout-2.2.2\include;..\..\libogg-1.1.3\include;..\..\pthreads-w32-2-9-1;..\..\libshout-2.2.2\win32\include;%(AdditionalIncludeDirectories) + _TIMESPEC_DEFINED;WIN32;_LIB;_WIN32;VERSION="2.0.0";LIBSHOUT_MAJOR=2;LIBSHOUT_MINOR=0;LIBSHOUT_MICRO=0;HAVE_WINSOCK2_H;_CRT_SECURE_NO_DEPRECATE;_CRT_NONSTDC_NO_DEPRECATE;%(PreprocessorDefinitions) + true + MultiThreaded + true + TurnOffAllWarnings + true + + + NDEBUG;%(PreprocessorDefinitions) + 0x0409 + + + true + + + + + Disabled + .\;..\..\libshout-2.2.2\src;..\..\libshout-2.2.2\include;..\..\libogg-1.1.3\include;..\..\pthreads-w32-2-9-1;..\..\libshout-2.2.2\win32\include;%(AdditionalIncludeDirectories) + _TIMESPEC_DEFINED;WIN32;_DEBUG;_LIB;_WIN32;VERSION="2.0.0";LIBSHOUT_MAJOR=2;LIBSHOUT_MINOR=0;LIBSHOUT_MICRO=0;HAVE_WINSOCK2_H;_CRT_SECURE_NO_DEPRECATE;_CRT_NONSTDC_NO_DEPRECATE;%(PreprocessorDefinitions) + true + EnableFastChecks + MultiThreadedDebug + TurnOffAllWarnings + true + + + _DEBUG;%(PreprocessorDefinitions) + 0x0409 + + + true + + + + + X64 + + + Disabled + .\;..\..\libshout-2.2.2\src;..\..\libshout-2.2.2\include;..\..\libogg-1.1.3\include;..\..\pthreads-w32-2-9-1;..\..\libshout-2.2.2\win32\include;%(AdditionalIncludeDirectories) + _TIMESPEC_DEFINED;WIN32;_DEBUG;_LIB;_WIN32;VERSION="2.0.0";LIBSHOUT_MAJOR=2;LIBSHOUT_MINOR=0;LIBSHOUT_MICRO=0;HAVE_WINSOCK2_H;_CRT_SECURE_NO_DEPRECATE;_CRT_NONSTDC_NO_DEPRECATE;%(PreprocessorDefinitions) + true + EnableFastChecks + MultiThreadedDebug + TurnOffAllWarnings + true + + + _DEBUG;%(PreprocessorDefinitions) + 0x0409 + + + true + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + {0feeaec6-4399-4c46-b7db-62ece80d15b4} + false + + + {df018947-0fff-4eb3-bdee-441dc81da7a4} + + + + + \ No newline at end of file diff --git a/scripts/debian_min_build.sh b/scripts/debian_min_build.sh index 953f3840ad..b585c1921e 100755 --- a/scripts/debian_min_build.sh +++ b/scripts/debian_min_build.sh @@ -8,7 +8,7 @@ wget -O - https://files.freeswitch.org/repo/deb/debian/freeswitch_archive_g0.pub echo "deb http://files.freeswitch.org/repo/deb/freeswitch-1.6/ jessie main" > /etc/apt/sources.list.d/freeswitch.list -apt-get update && apt-get install -y libtool libjpeg62-turbo-dev ntpdate libfreetype6-dev git-buildpackage doxygen yasm gdb git build-essential automake autoconf wget uuid-dev zlib1g-dev libncurses5-dev libssl-dev libpcre3-dev libcurl4-openssl-dev libldns-dev libedit-dev libspeexdsp-dev libsqlite3-dev perl libgdbm-dev libdb-dev bison pkg-config ccache libpng16-dev libpng12-dev libopenal-dev libbroadvoice-dev libcodec2-dev libflite-dev libg7221-dev libilbc-dev libsilk-dev liblua5.2-dev libopus-dev libsndfile-dev libavformat-dev libavcodec-extra libx264-dev libperl-dev unixodbc-dev libpq-dev libsctp-dev +apt-get update && apt-get install -y libtool libjpeg62-turbo-dev ntpdate libfreetype6-dev git-buildpackage doxygen yasm gdb git build-essential automake autoconf wget uuid-dev zlib1g-dev libncurses5-dev libssl-dev libpcre3-dev libcurl4-openssl-dev libldns-dev libedit-dev libspeexdsp-dev libsqlite3-dev perl libgdbm-dev libdb-dev bison pkg-config ccache libpng16-dev libpng12-dev libopenal-dev libbroadvoice-dev libcodec2-dev libflite-dev libg7221-dev libilbc-dev libsilk-dev liblua5.2-dev libopus-dev libsndfile-dev libavformat-dev libavcodec-extra libswscale-dev libx264-dev libperl-dev unixodbc-dev libpq-dev libsctp-dev cd /usr/src diff --git a/src/include/private/switch_apr_pvt.h b/src/include/private/switch_apr_pvt.h new file mode 100644 index 0000000000..ae4dc9c995 --- /dev/null +++ b/src/include/private/switch_apr_pvt.h @@ -0,0 +1,66 @@ +/* + * FreeSWITCH Modular Media Switching Software Library / Soft-Switch Application + * Copyright (C) 2005-2021, Anthony Minessale II + * + * Version: MPL 1.1 + * + * The contents of this file are subject to the Mozilla Public License Version + * 1.1 (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * http://www.mozilla.org/MPL/ + * + * Software distributed under the License is distributed on an "AS IS" basis, + * WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License + * for the specific language governing rights and limitations under the + * License. + * + * The Original Code is FreeSWITCH Modular Media Switching Software Library / Soft-Switch Application + * + * The Initial Developer of the Original Code is + * Anthony Minessale II + * Portions created by the Initial Developer are Copyright (C) + * the Initial Developer. All Rights Reserved. + * + * Contributor(s): + * + * Anthony Minessale II + * Andrey Volk + * + * + * switch_apr_pvt.h - APR + * + */ + +#ifndef __SWITCH_APR_PVT_H__ +#define __SWITCH_APR_PVT_H__ + +/* for apr_pool_create and apr_pool_destroy */ +/* functions only used in this file so not exposed */ +#include + +/* for apr_hash_make, apr_hash_pool_get, apr_hash_set */ +/* functions only used in this file so not exposed */ +#include + +/* for apr_pvsprintf */ +/* function only used in this file so not exposed */ +#include + +/* for apr_initialize and apr_terminate */ +/* function only used in this file so not exposed */ +#include + +#include + +#endif // __SWITCH_APR_PVT_H__ + +/* For Emacs: + * Local Variables: + * mode:c + * indent-tabs-mode:t + * tab-width:4 + * c-basic-offset:4 + * End: + * For VIM: + * vim:set softtabstop=4 shiftwidth=4 tabstop=4 noet: + */ diff --git a/src/include/private/switch_core_pvt.h b/src/include/private/switch_core_pvt.h index 388813701f..af6a4f53bd 100644 --- a/src/include/private/switch_core_pvt.h +++ b/src/include/private/switch_core_pvt.h @@ -32,32 +32,12 @@ * this file does not exist!!!! * */ -#define SPANDSP_NO_TIFF 1 -#include "spandsp.h" #include "switch_profile.h" #ifndef WIN32 #include #endif -/* for apr_pool_create and apr_pool_destroy */ -/* functions only used in this file so not exposed */ -#include - -/* for apr_hash_make, apr_hash_pool_get, apr_hash_set */ -/* functions only used in this file so not exposed */ -#include - -/* for apr_pvsprintf */ -/* function only used in this file so not exposed */ -#include - -/* for apr_initialize and apr_terminate */ -/* function only used in this file so not exposed */ -#include - -#include - #ifdef HAVE_MLOCKALL #include #endif @@ -175,7 +155,7 @@ struct switch_core_session { switch_log_level_t loglevel; uint32_t soft_lock; switch_ivr_dmachine_t *dmachine[2]; - plc_state_t *plc; + switch_plc_state_t *plc; switch_media_handle_t *media_handle; uint32_t decoder_errors; @@ -189,6 +169,7 @@ struct switch_core_session { switch_buffer_t *text_buffer; switch_buffer_t *text_line_buffer; switch_mutex_t *text_mutex; + const char *external_id; }; struct switch_media_bug { @@ -305,6 +286,7 @@ struct switch_runtime { uint32_t port_alloc_flags; char *event_channel_key_separator; uint32_t max_audio_channels; + switch_call_cause_t shutdown_cause; }; extern struct switch_runtime runtime; diff --git a/src/include/switch.h b/src/include/switch.h index 9fdbf12aa6..b7bae46c0e 100644 --- a/src/include/switch.h +++ b/src/include/switch.h @@ -112,6 +112,7 @@ #include "switch_platform.h" #include "switch_types.h" #include "switch_apr.h" +#include "switch_spandsp.h" #include "switch_mprintf.h" #include "switch_core_db.h" #include "switch_dso.h" @@ -136,6 +137,7 @@ #include "switch_core_event_hook.h" #include "switch_scheduler.h" #include "switch_config.h" +#include "switch_packetizer.h" #include "switch_nat.h" #include "switch_odbc.h" #include "switch_json.h" diff --git a/src/include/switch_channel.h b/src/include/switch_channel.h index 3786d4583c..5ee73c41fa 100644 --- a/src/include/switch_channel.h +++ b/src/include/switch_channel.h @@ -278,6 +278,8 @@ SWITCH_DECLARE(switch_status_t) switch_channel_get_log_tags(switch_channel_t *ch SWITCH_DECLARE(switch_status_t) switch_channel_set_variable_var_check(switch_channel_t *channel, const char *varname, const char *value, switch_bool_t var_check); +SWITCH_DECLARE(switch_status_t) switch_channel_set_variable_strip_quotes_var_check(switch_channel_t *channel, + const char *varname, const char *value, switch_bool_t var_check); SWITCH_DECLARE(switch_status_t) switch_channel_add_variable_var_check(switch_channel_t *channel, const char *varname, const char *value, switch_bool_t var_check, switch_stack_t stack); SWITCH_DECLARE(switch_status_t) switch_channel_set_variable_printf(switch_channel_t *channel, const char *varname, const char *fmt, ...); @@ -295,6 +297,7 @@ SWITCH_DECLARE(switch_status_t) switch_channel_transfer_variable_prefix(switch_c #define switch_channel_set_variable_safe(_channel, _var, _val) switch_channel_set_variable_var_check(_channel, _var, _val, SWITCH_FALSE) #define switch_channel_set_variable(_channel, _var, _val) switch_channel_set_variable_var_check(_channel, _var, _val, SWITCH_TRUE) +#define switch_channel_set_variable_strip_quotes(_channel, _var, _val) switch_channel_set_variable_strip_quotes_var_check(_channel, _var, _val, SWITCH_TRUE) #define switch_channel_set_variable_partner(_channel, _var, _val) switch_channel_set_variable_partner_var_check(_channel, _var, _val, SWITCH_TRUE) @@ -323,7 +326,7 @@ SWITCH_DECLARE(const char *) switch_channel_get_variable_dup(switch_channel_t *c #define switch_channel_get_variable(_c, _v) switch_channel_get_variable_dup(_c, _v, SWITCH_TRUE, -1) SWITCH_DECLARE(switch_status_t) switch_channel_get_variables(switch_channel_t *channel, switch_event_t **event); - +SWITCH_DECLARE(switch_status_t) switch_channel_get_variables_prefix(switch_channel_t *channel, const char *prefix, switch_event_t **event); SWITCH_DECLARE(switch_status_t) switch_channel_pass_callee_id(switch_channel_t *channel, switch_channel_t *other_channel); static inline int switch_channel_var_false(switch_channel_t *channel, const char *variable) { @@ -682,6 +685,7 @@ SWITCH_DECLARE(void) switch_channel_mark_hold(switch_channel_t *channel, switch_ /** @} */ SWITCH_DECLARE(switch_status_t) switch_channel_execute_on(switch_channel_t *channel, const char *variable_prefix); +SWITCH_DECLARE(switch_status_t) switch_channel_execute_on_value(switch_channel_t *channel, const char *variable_value); SWITCH_DECLARE(switch_status_t) switch_channel_api_on(switch_channel_t *channel, const char *variable_prefix); SWITCH_DECLARE(void) switch_channel_process_device_hangup(switch_channel_t *channel); SWITCH_DECLARE(switch_caller_extension_t *) switch_channel_get_queued_extension(switch_channel_t *channel); diff --git a/src/include/switch_core.h b/src/include/switch_core.h index 4f172a928e..e4c615941d 100644 --- a/src/include/switch_core.h +++ b/src/include/switch_core.h @@ -1,6 +1,6 @@ /* * FreeSWITCH Modular Media Switching Software Library / Soft-Switch Application - * Copyright (C) 2005-2014, Anthony Minessale II + * Copyright (C) 2005-2020, Anthony Minessale II * * Version: MPL 1.1 * @@ -67,6 +67,7 @@ typedef struct switch_thread_data_s { switch_thread_start_t func; void *obj; int alloc; + int running; switch_memory_pool_t *pool; } switch_thread_data_t; @@ -243,14 +244,6 @@ static inline void *switch_must_realloc(void *_b, size_t _z) return m; } -static inline char *switch_must_strdup(const char *_s) -{ - char *s = strdup(_s); - switch_assert(s); - return s; -} - - /*! \defgroup core1 Core Library \ingroup FREESWITCH @@ -811,6 +804,8 @@ SWITCH_DECLARE(switch_core_session_t *) switch_core_session_request_uuid(_In_ sw SWITCH_DECLARE(switch_status_t) switch_core_session_set_uuid(_In_ switch_core_session_t *session, _In_z_ const char *use_uuid); +SWITCH_DECLARE(switch_status_t) switch_core_session_set_external_id(_In_ switch_core_session_t *session, _In_z_ const char *use_external_id); + SWITCH_DECLARE(void) switch_core_session_perform_destroy(_Inout_ switch_core_session_t **session, _In_z_ const char *file, _In_z_ const char *func, _In_ int line); @@ -859,7 +854,8 @@ SWITCH_DECLARE(switch_status_t) switch_core_session_thread_launch(_In_ switch_co SWITCH_DECLARE(switch_status_t) switch_thread_pool_launch_thread(switch_thread_data_t **tdp); SWITCH_DECLARE(switch_status_t) switch_core_session_thread_pool_launch(switch_core_session_t *session); - +SWITCH_DECLARE(switch_status_t) switch_thread_pool_wait(switch_thread_data_t *td, int ms); + /*! \brief Retrieve a pointer to the channel object associated with a given session \param session the session to retrieve from @@ -881,6 +877,13 @@ SWITCH_DECLARE(void) switch_core_session_signal_state_change(_In_ switch_core_se */ SWITCH_DECLARE(char *) switch_core_session_get_uuid(_In_ switch_core_session_t *session); +/*! + \brief Retrieve the unique external identifier from a session + \param session the session to retrieve the uuid from + \return a string representing the uuid +*/ +SWITCH_DECLARE(const char *) switch_core_session_get_external_id(_In_ switch_core_session_t *session); + /*! \brief Sets the log level for a session @@ -1436,6 +1439,14 @@ SWITCH_DECLARE(switch_status_t) switch_core_hash_init_case(_Out_ switch_hash_t * */ SWITCH_DECLARE(switch_status_t) switch_core_hash_destroy(_Inout_ switch_hash_t **hash); +/*! + \brief Insert data into a hash with an auto-generated key based on the data pointer + \param hash the hash to add data to + \param data unique pointer to add + \return SWITCH_STATUS_SUCCESS if the data is added +*/ +SWITCH_DECLARE(switch_status_t) switch_core_hash_insert_pointer(switch_hash_t *hash, const void *data); + /*! \brief Insert data into a hash and set flags so the value is automatically freed on delete \param hash the hash to add data to @@ -1446,6 +1457,16 @@ SWITCH_DECLARE(switch_status_t) switch_core_hash_destroy(_Inout_ switch_hash_t * */ SWITCH_DECLARE(switch_status_t) switch_core_hash_insert_auto_free(switch_hash_t *hash, const char *key, const void *data); +/*! + \brief Insert strdup(str) into a hash and set flags so the value is automatically freed on delete + \param hash the hash to add str to + \param key the name of the key to add the str to + \param str string to strdup and add + \return SWITCH_STATUS_SUCCESS if the data is added + \note the string key must be a constant or a dynamic string +*/ +SWITCH_DECLARE(switch_status_t) switch_core_hash_insert_dup_auto_free(switch_hash_t *hash, const char *key, const char *str); + /*! \brief Insert data into a hash \param hash the hash to add data to @@ -1457,6 +1478,28 @@ SWITCH_DECLARE(switch_status_t) switch_core_hash_insert_auto_free(switch_hash_t SWITCH_DECLARE(switch_status_t) switch_core_hash_insert_destructor(_In_ switch_hash_t *hash, _In_z_ const char *key, _In_opt_ const void *data, hashtable_destructor_t destructor); #define switch_core_hash_insert(_h, _k, _d) switch_core_hash_insert_destructor(_h, _k, _d, NULL) +/*! + \brief Allocate memory and insert into a hash + \param hash the hash to add data to + \param key the name of the key to add the data to + \param size the size in bytes to allocate + \return pointer to the allocated memory + \note the string key must be a constant or a dynamic string +*/ +SWITCH_DECLARE(void *) switch_core_hash_insert_alloc_destructor(_In_ switch_hash_t *hash, _In_z_ const char *key, _In_opt_ size_t size, hashtable_destructor_t destructor); +#define switch_core_hash_insert_alloc(_h, _k, _s) switch_core_hash_insert_alloc_destructor(_h, _k, _s, NULL) + +/*! + \brief Insert strdup(str) into a hash + \param hash the hash to add str to + \param key the name of the key to add the str to + \param str string to strdup and add + \return SWITCH_STATUS_SUCCESS if the data is added + \note the string key must be a constant or a dynamic string +*/ +SWITCH_DECLARE(switch_status_t) switch_core_hash_insert_dup_destructor(_In_ switch_hash_t *hash, _In_z_ const char *key, _In_opt_ const char *str, hashtable_destructor_t destructor); +#define switch_core_hash_insert_dup(_h, _k, _d) switch_core_hash_insert_dup_destructor(_h, _k, _d, NULL) + /*! \brief Insert data into a hash diff --git a/src/include/switch_core_media.h b/src/include/switch_core_media.h index cb454c4983..f57e1ce974 100644 --- a/src/include/switch_core_media.h +++ b/src/include/switch_core_media.h @@ -49,6 +49,12 @@ typedef enum { DTMF_NONE } switch_core_media_dtmf_t; +typedef enum { + AVP_NO_SECURE, + AVP_SECURE, + AVP_UNDEFINED +} switch_core_media_avp_secure_t; + typedef enum { SM_NDLB_ALLOW_BAD_IANANAME = (1 << 0), SM_NDLB_ALLOW_NONDUP_SDP = (1 << 1), @@ -207,6 +213,7 @@ SWITCH_DECLARE(int) switch_core_session_check_incoming_crypto(switch_core_sessio SWITCH_DECLARE(uint32_t) switch_core_media_get_video_fps(switch_core_session_t *session); SWITCH_DECLARE(void) switch_core_media_set_rtp_session(switch_core_session_t *session, switch_media_type_t type, switch_rtp_t *rtp_session); +SWITCH_DECLARE(switch_rtp_t *) switch_core_media_get_rtp_session(switch_core_session_t *session, switch_media_type_t type); SWITCH_DECLARE(const char *)switch_core_media_get_codec_string(switch_core_session_t *session); SWITCH_DECLARE(void) switch_core_media_parse_rtp_bugs(switch_rtp_bug_flag_t *flag_pole, const char *str); @@ -248,6 +255,8 @@ SWITCH_DECLARE(switch_core_media_params_t *) switch_core_media_get_mparams(switc SWITCH_DECLARE(void) switch_core_media_prepare_codecs(switch_core_session_t *session, switch_bool_t force); SWITCH_DECLARE(void) switch_core_media_start_udptl(switch_core_session_t *session, switch_t38_options_t *t38_options); SWITCH_DECLARE(void) switch_core_media_hard_mute(switch_core_session_t *session, switch_bool_t on); +SWITCH_DECLARE(cJSON *) switch_core_media_gen_json_constraint(float min, float ideal, float max); +SWITCH_DECLARE(switch_status_t) switch_core_media_media_params(switch_core_session_t *session, const char *json); SWITCH_DECLARE(switch_status_t) switch_core_media_receive_message(switch_core_session_t *session, switch_core_session_message_t *msg); @@ -389,7 +398,10 @@ SWITCH_DECLARE(switch_status_t) switch_core_session_printf(switch_core_session_t SWITCH_DECLARE(switch_msrp_session_t *) switch_core_media_get_msrp_session(switch_core_session_t *session); SWITCH_DECLARE(void) switch_core_media_set_smode(switch_core_session_t *session, switch_media_type_t type, switch_media_flow_t smode, switch_sdp_type_t sdp_type); - + +SWITCH_DECLARE(void) switch_core_media_set_resolveice(switch_bool_t resolve_ice); +SWITCH_DECLARE(switch_bool_t) switch_core_media_has_resolveice(void); + SWITCH_END_EXTERN_C #endif /* For Emacs: diff --git a/src/include/switch_core_video.h b/src/include/switch_core_video.h index e152922675..1af0dec7ac 100644 --- a/src/include/switch_core_video.h +++ b/src/include/switch_core_video.h @@ -390,11 +390,22 @@ SWITCH_DECLARE(void) switch_img_patch_hole(switch_image_t *IMG, switch_image_t * SWITCH_DECLARE(switch_status_t) switch_png_patch_img(switch_png_t *use_png, switch_image_t *img, int x, int y); SWITCH_DECLARE(switch_image_t *) switch_img_read_png(const char *file_name, switch_img_fmt_t img_fmt); +SWITCH_DECLARE(switch_image_t *) switch_img_read_png_from_memory(void *mem, size_t size, switch_img_fmt_t img_fmt); SWITCH_DECLARE(switch_status_t) switch_img_write_png(switch_image_t *img, char *file_name); SWITCH_DECLARE(switch_status_t) switch_png_open(switch_png_t **pngP, const char *file_name); SWITCH_DECLARE(void) switch_png_free(switch_png_t **pngP); SWITCH_DECLARE(switch_status_t) switch_img_data_url_png(switch_image_t *img, char **urlP); - +SWITCH_DECLARE(switch_status_t) switch_img_data_url(switch_image_t *img, char **urlP, const char *type, int quality); + +/*!\brief Read an image file to switch_image_t */ +SWITCH_DECLARE(switch_image_t *) switch_img_read_from_file(const char *file_name, switch_img_fmt_t img_fmt); +/*!\brief Write an image file, supported formats png,jpg,bmp,tga,hdr +* \param[in] img The image descriptor +* \param[in] file_name The file_name to write +* \param[in] quality Only used in jpg, 1 ~ 100 +*/ +SWITCH_DECLARE(switch_status_t) switch_img_write_to_file(switch_image_t *img, const char* file_name, int quality); + /*!\brief put a small img over a big IMG at position x,y, with alpha transparency * * Both IMG and img must be non-NULL @@ -410,6 +421,7 @@ SWITCH_DECLARE(void) switch_img_overlay(switch_image_t *IMG, switch_image_t *img SWITCH_DECLARE(switch_status_t) switch_img_mirror(switch_image_t *src, switch_image_t **destP); SWITCH_DECLARE(switch_status_t) switch_img_scale(switch_image_t *src, switch_image_t **destP, int width, int height); SWITCH_DECLARE(switch_status_t) switch_img_fit(switch_image_t **srcP, int width, int height, switch_img_fit_t fit); +SWITCH_DECLARE(void) switch_img_calc_fit(switch_image_t *src, int width, int height, int *new_wP, int *new_hP); SWITCH_DECLARE(switch_img_position_t) parse_img_position(const char *name); SWITCH_DECLARE(switch_img_fit_t) parse_img_fit(const char *name); SWITCH_DECLARE(void) switch_img_find_position(switch_img_position_t pos, int sw, int sh, int iw, int ih, int *xP, int *yP); diff --git a/src/include/switch_ivr.h b/src/include/switch_ivr.h index 09577152b4..33fd297da8 100644 --- a/src/include/switch_ivr.h +++ b/src/include/switch_ivr.h @@ -438,7 +438,19 @@ SWITCH_DECLARE(switch_status_t) switch_ivr_gentones(switch_core_session_t *sessi SWITCH_DECLARE(switch_status_t) switch_ivr_record_file(_In_ switch_core_session_t *session, _In_ switch_file_handle_t *fh, _In_z_ const char *file, _In_opt_ switch_input_args_t *args, _In_ uint32_t limit); - +/*! + \brief record a file from the session to a file + \param session the session to record from + \param fh file handle to use + \param file the path to the file + \param args arguements to pass for callbacks etc + \param limit max limit to record for (0 for infinite) + \param vars vars to add to RECORD_START and RECORD_STOP automatically prefixed with Recording-Variable- + \return SWITCH_STATUS_SUCCESS if all is well +*/ +SWITCH_DECLARE(switch_status_t) switch_ivr_record_file_event(_In_ switch_core_session_t *session, + _In_ switch_file_handle_t *fh, + _In_z_ const char *file, _In_opt_ switch_input_args_t *args, _In_ uint32_t limit, switch_event_t *vars); /*! \brief Play a sound and gather digits with the number of retries specified if the user doesn't give digits in the set time @@ -1031,6 +1043,7 @@ SWITCH_DECLARE(char *) switch_ivr_check_presence_mapping(const char *exten_name, SWITCH_DECLARE(switch_status_t) switch_ivr_kill_uuid(const char *uuid, switch_call_cause_t cause); SWITCH_DECLARE(switch_status_t) switch_ivr_blind_transfer_ack(switch_core_session_t *session, switch_bool_t success); SWITCH_DECLARE(switch_status_t) switch_ivr_record_session_mask(switch_core_session_t *session, const char *file, switch_bool_t on); +SWITCH_DECLARE(switch_status_t) switch_ivr_record_session_pause(switch_core_session_t *session, const char *file, switch_bool_t on); SWITCH_DECLARE(switch_status_t) switch_ivr_stop_video_write_overlay_session(switch_core_session_t *session); @@ -1069,7 +1082,8 @@ SWITCH_DECLARE(void) switch_dial_handle_list_add_global_var(switch_dial_handle_l SWITCH_DECLARE(void) switch_dial_handle_list_add_global_var_printf(switch_dial_handle_list_t *hl, const char *var, const char *fmt, ...); SWITCH_DECLARE(switch_status_t) switch_ivr_enterprise_orig_and_bridge(switch_core_session_t *session, const char *data, switch_dial_handle_list_t *hl, switch_call_cause_t *cause); SWITCH_DECLARE(switch_status_t) switch_ivr_orig_and_bridge(switch_core_session_t *session, const char *data, switch_dial_handle_t *dh, switch_call_cause_t *cause); - +SWITCH_DECLARE(switch_status_t) switch_ivr_send_prompt(switch_core_session_t *session, const char *type, const char *text, const char *regex); + SWITCH_DECLARE(switch_status_t) switch_ivr_play_and_collect_input(switch_core_session_t *session, const char *prompt, const char *recognizer_mod_name, diff --git a/src/include/switch_log.h b/src/include/switch_log.h index 8fb0beae2a..ee8f0d02ae 100644 --- a/src/include/switch_log.h +++ b/src/include/switch_log.h @@ -66,6 +66,10 @@ SWITCH_BEGIN_EXTERN_C switch_text_channel_t channel; switch_log_level_t slevel; switch_event_t *tags; + /* Log sequence */ + int64_t sequence; + /* Optional extra log metadata */ + cJSON *meta; } switch_log_node_t; ///\{ @@ -94,6 +98,7 @@ typedef struct { switch_log_json_format_item_t short_message; const char *custom_field_prefix; double timestamp_divisor; + switch_log_json_format_item_t sequence; } switch_log_json_format_t; typedef switch_status_t (*switch_log_function_t) (const switch_log_node_t *node, switch_log_level_t level); @@ -154,7 +159,40 @@ SWITCH_DECLARE(void) switch_log_printf(_In_ switch_text_channel_t channel, _In_z SWITCH_DECLARE(void) switch_log_vprintf(_In_ switch_text_channel_t channel, _In_z_ const char *file, _In_z_ const char *func, _In_ int line, _In_opt_z_ const char *userdata, _In_ switch_log_level_t level, const char *fmt, va_list ap); +/*! + \brief Write log data to the logging engine w/ optional JSON metadata + \param channel the log channel to write to + \param file the current file + \param func the current function + \param line the current line + \param userdata ununsed + \param level the current log level + \param meta log metadata - consumed by this function + \param fmt desired format + \param ... variable args + \note there are channel macros to supply the first 4 parameters (SWITCH_CHANNEL_LOG, SWITCH_CHANNEL_LOG_CLEAN, ...) + \see switch_types.h +*/ +SWITCH_DECLARE(void) switch_log_meta_printf(switch_text_channel_t channel, const char *file, const char *func, int line, + const char *userdata, switch_log_level_t level, cJSON **meta, const char *fmt, ...) PRINTF_FUNCTION(8, 9); +/*! + \brief Write log data to the logging engine w/ optional JSON metadata + \param channel the log channel to write to + \param file the current file + \param func the current function + \param line the current line + \param userdata ununsed + \param level the current log level + \param meta log metadata - consumed by this function + \param fmt desired format + \param ap variable args + \note there are channel macros to supply the first 4 parameters (SWITCH_CHANNEL_LOG, SWITCH_CHANNEL_LOG_CLEAN, ...) + \see switch_types.h +*/ +SWITCH_DECLARE(void) switch_log_meta_vprintf(_In_ switch_text_channel_t channel, _In_z_ const char *file, + _In_z_ const char *func, _In_ int line, + _In_opt_z_ const char *userdata, _In_ switch_log_level_t level, cJSON **meta, const char *fmt, va_list ap); #endif /*! \brief Shut down the logging engine diff --git a/src/include/switch_packetizer.h b/src/include/switch_packetizer.h new file mode 100644 index 0000000000..b6079d6c08 --- /dev/null +++ b/src/include/switch_packetizer.h @@ -0,0 +1,60 @@ +/* + * FreeSWITCH Modular Media Switching Software Library / Soft-Switch Application + * Copyright (C) 2005-2020, Anthony Minessale II + * + * Version: MPL 1.1 + * + * The contents of this file are subject to the Mozilla Public License Version + * 1.1 (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * http://www.mozilla.org/MPL/ + * + * Software distributed under the License is distributed on an "AS IS" basis, + * WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License + * for the specific language governing rights and limitations under the + * License. + * + * The Original Code is FreeSWITCH Modular Media Switching Software Library / Soft-Switch Application + * + * The Initial Developer of the Original Code is + * Seven Du + * Portions created by the Initial Developer are Copyright (C) + * the Initial Developer. All Rights Reserved. + * + * Contributor(s): + * + * Seven Du + * + * switch_packetizer H264 packetizer + * + */ + +#ifndef SWITCH_PACKETIZER_H +#define SWITCH_PACKETIZER_H + +typedef void switch_packetizer_t; + +typedef enum { + SPT_H264_BITSTREAM, // with separator 0 0 0 1 or 0 0 1 + SPT_H264_SIZED_BITSTREAM, + SPT_H264_SIGNALE_NALU, + SPT_VP8_BITSTREAM, + SPT_VP9_BITSTREAM, + + // no more beyond this line + SPT_INVALID_STREAM +} switch_packetizer_bitstream_t; + +/* + + create a packetizer and feed data, to avoid data copy, data MUST be valid before the next feed, or before close. + + */ + +SWITCH_DECLARE(switch_packetizer_t *) switch_packetizer_create(switch_packetizer_bitstream_t type, uint32_t slice_size); +SWITCH_DECLARE(switch_status_t) switch_packetizer_feed(switch_packetizer_t *packetizer, void *data, uint32_t size); +SWITCH_DECLARE(switch_status_t) switch_packetizer_feed_extradata(switch_packetizer_t *packetizer, void *data, uint32_t size); +SWITCH_DECLARE(switch_status_t) switch_packetizer_read(switch_packetizer_t *packetizer, switch_frame_t *frame); +SWITCH_DECLARE(void) switch_packetizer_close(switch_packetizer_t **packetizer); + +#endif diff --git a/src/include/switch_private.h.cmake b/src/include/switch_private.h.cmake index dc94b73a88..d55a8d4169 100644 --- a/src/include/switch_private.h.cmake +++ b/src/include/switch_private.h.cmake @@ -22,9 +22,6 @@ /* Define to 1 if you have the header file. */ #cmakedefine HAVE_DLFCN_H -/* Define to 1 if you have the header file. */ -#cmakedefine HAVE_EXECINFO_H - /* Define to 1 if you have the `gethostname' function. */ #cmakedefine HAVE_GETHOSTNAME diff --git a/src/include/switch_rtp.h b/src/include/switch_rtp.h index 96ea2135f3..3da7254e91 100644 --- a/src/include/switch_rtp.h +++ b/src/include/switch_rtp.h @@ -41,9 +41,11 @@ SWITCH_BEGIN_EXTERN_C +#define SWITCH_RTP_HEADER_LEN sizeof(switch_rtp_hdr_t) #define SWITCH_RTP_MAX_BUF_LEN 16384 #define SWITCH_RTCP_MAX_BUF_LEN 16384 #define SWITCH_RTP_MAX_BUF_LEN_WORDS 4094 /* (max / 4) - 2 */ +#define SWITCH_RTP_MAX_PACKET_LEN (SWITCH_RTP_MAX_BUF_LEN + SWITCH_RTP_HEADER_LEN) //#define SWITCH_RTP_KEY_LEN 30 //#define SWITCH_RTP_CRYPTO_KEY_32 "AES_CM_128_HMAC_SHA1_32" #define SWITCH_RTP_CRYPTO_KEY_80 "AES_CM_128_HMAC_SHA1_80" diff --git a/src/include/switch_spandsp.h b/src/include/switch_spandsp.h new file mode 100644 index 0000000000..1818a00825 --- /dev/null +++ b/src/include/switch_spandsp.h @@ -0,0 +1,54 @@ +/* + * FreeSWITCH Modular Media Switching Software Library / Soft-Switch Application + * Copyright (C) 2005-2014, Anthony Minessale II + * + * Version: MPL 1.1 + * + * The contents of this file are subject to the Mozilla Public License Version + * 1.1 (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * http://www.mozilla.org/MPL/ + * + * Software distributed under the License is distributed on an "AS IS" basis, + * WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License + * for the specific language governing rights and limitations under the + * License. + * + * The Original Code is FreeSWITCH Modular Media Switching Software Library / Soft-Switch Application + * + * The Initial Developer of the Original Code is + * Anthony Minessale II + * Portions created by the Initial Developer are Copyright (C) + * the Initial Developer. All Rights Reserved. + * + * Contributor(s): + * + * Anthony Minessale II + * Andrey Volk + * + * switch_spandsp.h -- SpanDSP includes header + * + */ +#ifndef SWITCH_SPANDSP_H +#define SWITCH_SPANDSP_H + +SWITCH_BEGIN_EXTERN_C + +SWITCH_DECLARE(switch_plc_state_t *) switch_plc_init(switch_plc_state_t *s); +SWITCH_DECLARE(int) switch_plc_free(switch_plc_state_t *s); +SWITCH_DECLARE(int) switch_plc_rx(switch_plc_state_t *s, int16_t amp[], int len); +SWITCH_DECLARE(int) switch_plc_fillin(switch_plc_state_t *s, int16_t amp[], int len); + +SWITCH_END_EXTERN_C +#endif + +/* For Emacs: + * Local Variables: + * mode:c + * indent-tabs-mode:t + * tab-width:4 + * c-basic-offset:4 + * End: + * For VIM: + * vim:set softtabstop=4 shiftwidth=4 tabstop=4 noet: + */ diff --git a/src/include/switch_types.h b/src/include/switch_types.h index fafc508823..b8405511d8 100644 --- a/src/include/switch_types.h +++ b/src/include/switch_types.h @@ -843,6 +843,9 @@ typedef enum { SWITCH_RTP_FLAG_PASSTHRU, SWITCH_RTP_FLAG_SECURE_SEND_MKI, SWITCH_RTP_FLAG_SECURE_RECV_MKI, + SWITCH_RTP_FLAG_SRTP_HANGUP_ON_ERROR, + SWITCH_RTP_FLAG_AUDIO_FIRE_SEND_RTCP_EVENT, + SWITCH_RTP_FLAG_VIDEO_FIRE_SEND_RTCP_EVENT, SWITCH_RTP_FLAG_INVALID } switch_rtp_flag_t; @@ -1135,6 +1138,7 @@ typedef enum { SWITCH_MESSAGE_INDICATE_DEFLECT, SWITCH_MESSAGE_INDICATE_VIDEO_REFRESH_REQ, SWITCH_MESSAGE_INDICATE_DISPLAY, + SWITCH_MESSAGE_INDICATE_MEDIA_PARAMS, SWITCH_MESSAGE_INDICATE_TRANSCODING_NECESSARY, SWITCH_MESSAGE_INDICATE_AUDIO_SYNC, SWITCH_MESSAGE_INDICATE_VIDEO_SYNC, @@ -1171,6 +1175,7 @@ typedef enum { SWITCH_MESSAGE_RESAMPLE_EVENT, SWITCH_MESSAGE_HEARTBEAT_EVENT, SWITCH_MESSAGE_INDICATE_SESSION_ID, + SWITCH_MESSAGE_INDICATE_PROMPT, SWITCH_MESSAGE_INVALID } switch_core_session_message_types_t; @@ -1324,13 +1329,17 @@ typedef enum { } switch_core_session_message_flag_enum_t; typedef uint32_t switch_core_session_message_flag_t; +typedef struct switch_core_session switch_core_session_t; +static inline switch_core_session_t *switch_core_session_type_check(switch_core_session_t *session) { return session; } +static inline const char *switch_const_char_type_check(const char *str) { return str; } + #define SWITCH_CHANNEL_LOG SWITCH_CHANNEL_ID_LOG, __FILE__, __SWITCH_FUNC__, __LINE__, NULL #define SWITCH_CHANNEL_LOG_CLEAN SWITCH_CHANNEL_ID_LOG_CLEAN, __FILE__, __SWITCH_FUNC__, __LINE__, NULL #define SWITCH_CHANNEL_SESSION_LOG_CLEAN(x) SWITCH_CHANNEL_ID_LOG_CLEAN, __FILE__, __SWITCH_FUNC__, __LINE__, switch_core_session_get_uuid((x)) #define SWITCH_CHANNEL_EVENT SWITCH_CHANNEL_ID_EVENT, __FILE__, __SWITCH_FUNC__, __LINE__, NULL -#define SWITCH_CHANNEL_SESSION_LOG(x) SWITCH_CHANNEL_ID_SESSION, __FILE__, __SWITCH_FUNC__, __LINE__, (const char*)(x) +#define SWITCH_CHANNEL_SESSION_LOG(x) SWITCH_CHANNEL_ID_SESSION, __FILE__, __SWITCH_FUNC__, __LINE__, (const char*)switch_core_session_type_check(x) #define SWITCH_CHANNEL_CHANNEL_LOG(x) SWITCH_CHANNEL_ID_SESSION, __FILE__, __SWITCH_FUNC__, __LINE__, (const char*)switch_channel_get_session(x) -#define SWITCH_CHANNEL_UUID_LOG(x) SWITCH_CHANNEL_ID_LOG, __FILE__, __SWITCH_FUNC__, __LINE__, (x) +#define SWITCH_CHANNEL_UUID_LOG(x) SWITCH_CHANNEL_ID_LOG, __FILE__, __SWITCH_FUNC__, __LINE__, switch_const_char_type_check(x) typedef enum { CCS_DOWN, @@ -1450,6 +1459,7 @@ typedef enum { CC_IO_OVERRIDE, CC_RTP_RTT, CC_MSRP, + CC_MUTE_VIA_MEDIA_STREAM, /* WARNING: DO NOT ADD ANY FLAGS BELOW THIS LINE */ CC_FLAG_MAX } switch_channel_cap_t; @@ -1529,6 +1539,7 @@ typedef enum { CF_INTERCEPTED, CF_VIDEO_REFRESH_REQ, CF_MANUAL_VID_REFRESH, + CF_MANUAL_MEDIA_PARAMS, CF_SERVICE_AUDIO, CF_SERVICE_VIDEO, CF_ZRTP_PASSTHRU_REQ, @@ -1562,6 +1573,7 @@ typedef enum { CF_T38_PASSTHRU, CF_DROP_DTMF, CF_REINVITE, + CF_NOSDP_REINVITE, CF_AUTOFLUSH_DURING_BRIDGE, CF_RTP_NOTIMER_DURING_BRIDGE, CF_AVPF, @@ -1589,7 +1601,7 @@ typedef enum { CF_VIDEO_DECODED_READ, CF_VIDEO_DEBUG_READ, CF_VIDEO_DEBUG_WRITE, - CF_VIDEO_ONLY, + CF_NO_RECOVER, CF_VIDEO_READY, CF_VIDEO_MIRROR_INPUT, CF_VIDEO_READ_FILE_ATTACHED, @@ -1623,6 +1635,10 @@ typedef enum { CF_STATE_REPEAT, CF_WANT_DTLSv1_2, CF_RFC7329_COMPAT, + CF_REATTACHED, + CF_VIDEO_READ_TAPPED, + CF_VIDEO_WRITE_TAPPED, + CF_DEVICES_CHANGED, /* WARNING: DO NOT ADD ANY FLAGS BELOW THIS LINE */ /* IF YOU ADD NEW ONES CHECK IF THEY SHOULD PERSIST OR ZERO THEM IN switch_core_session.c switch_core_session_request_xml() */ CF_FLAG_MAX @@ -1900,7 +1916,8 @@ typedef enum { SMBF_SPY_VIDEO_STREAM_BLEG = (1 << 23), SMBF_READ_VIDEO_PATCH = (1 << 24), SMBF_READ_TEXT_STREAM = (1 << 25), - SMBF_FIRST = (1 << 26) + SMBF_FIRST = (1 << 26), + SMBF_PAUSE = (1 << 27) } switch_media_bug_flag_enum_t; typedef uint32_t switch_media_bug_flag_t; @@ -2037,6 +2054,7 @@ typedef uint32_t switch_io_flag_t; SWITCH_EVENT_SEND_INFO SWITCH_EVENT_RECV_INFO SWITCH_EVENT_RECV_RTCP_MESSAGE + SWITCH_EVENT_SEND_RTCP_MESSAGE SWITCH_EVENT_CALL_SECURE SWITCH_EVENT_NAT - NAT Management (new/del/status) SWITCH_EVENT_RECORD_START @@ -2132,6 +2150,7 @@ typedef enum { SWITCH_EVENT_SEND_INFO, SWITCH_EVENT_RECV_INFO, SWITCH_EVENT_RECV_RTCP_MESSAGE, + SWITCH_EVENT_SEND_RTCP_MESSAGE, SWITCH_EVENT_CALL_SECURE, SWITCH_EVENT_NAT, SWITCH_EVENT_RECORD_START, @@ -2286,7 +2305,9 @@ typedef enum { SCSC_SPS_PEAK, SCSC_SPS_PEAK_FIVEMIN, SCSC_SESSIONS_PEAK, - SCSC_SESSIONS_PEAK_FIVEMIN + SCSC_SESSIONS_PEAK_FIVEMIN, + SCSC_MDNS_RESOLVE, + SCSC_SHUTDOWN_CAUSE } switch_session_ctl_t; typedef enum { @@ -2303,6 +2324,7 @@ typedef int switch_os_socket_t; #endif typedef struct apr_pool_t switch_memory_pool_t; +typedef void* switch_plc_state_t; typedef uint16_t switch_port_t; typedef uint8_t switch_payload_t; typedef struct switch_app_log switch_app_log_t; @@ -2319,7 +2341,6 @@ typedef struct switch_rtcp_frame switch_rtcp_frame_t; typedef struct switch_channel switch_channel_t; typedef struct switch_sql_queue_manager switch_sql_queue_manager_t; typedef struct switch_file_handle switch_file_handle_t; -typedef struct switch_core_session switch_core_session_t; typedef struct switch_caller_profile switch_caller_profile_t; typedef struct switch_caller_extension switch_caller_extension_t; typedef struct switch_caller_application switch_caller_application_t; @@ -2802,6 +2823,7 @@ typedef struct switch_mm_s { int cbr; float fps; float source_fps; + int source_kps; int vbuf; switch_video_profile_t vprofile; switch_video_encode_speed_t vencspd; diff --git a/src/include/switch_utils.h b/src/include/switch_utils.h index 24c6151331..62f3fcd97e 100644 --- a/src/include/switch_utils.h +++ b/src/include/switch_utils.h @@ -590,7 +590,7 @@ SWITCH_DECLARE(char *) get_addr(char *buf, switch_size_t len, struct sockaddr *s SWITCH_DECLARE(char *) get_addr6(char *buf, switch_size_t len, struct sockaddr_in6 *sa, socklen_t salen); SWITCH_DECLARE(int) get_addr_int(switch_sockaddr_t *sa); -SWITCH_DECLARE(int) switch_cmp_addr(switch_sockaddr_t *sa1, switch_sockaddr_t *sa2); +SWITCH_DECLARE(int) switch_cmp_addr(switch_sockaddr_t *sa1, switch_sockaddr_t *sa2, switch_bool_t ip_only); SWITCH_DECLARE(int) switch_cp_addr(switch_sockaddr_t *sa1, switch_sockaddr_t *sa2); /*! @@ -888,13 +888,10 @@ static inline char *switch_safe_strdup(const char *it) static inline char *switch_lc_strdup(const char *it) { char *dup; - char *p; if (it) { dup = strdup(it); - for (p = dup; p && *p; p++) { - *p = (char) switch_tolower(*p); - } + switch_tolower_max(dup); return dup; } @@ -905,13 +902,10 @@ static inline char *switch_lc_strdup(const char *it) static inline char *switch_uc_strdup(const char *it) { char *dup; - char *p; if (it) { dup = strdup(it); - for (p = dup; p && *p; p++) { - *p = (char) switch_toupper(*p); - } + switch_toupper_max(dup); return dup; } @@ -1150,10 +1144,7 @@ static inline uint32_t switch_parse_cpu_string(const char *cpu) if (!cpu) return 1; if (!strcasecmp(cpu, "auto")) { - if (cpu_count > 4) return 4; - if (cpu_count <= 2) return 1; - - return (uint32_t)(cpu_count / 2); + return (uint32_t)((cpu_count * 3) / 2); } if (!strncasecmp(cpu, "cpu/", 4)) { /* cpu/2 or cpu/2/ */ @@ -1289,6 +1280,31 @@ static inline switch_bool_t switch_is_file_path(const char *file) return r ? SWITCH_TRUE : SWITCH_FALSE; } +static inline int switch_filecmp(const char *a, const char *b) +{ + const char *e; + + if (zstr(a) || zstr(b)) { + return -1; + } + + while(*a == '{') { + if ((e = switch_find_end_paren(a, '{', '}'))) { + a = e + 1; + while(*a == ' ') a++; + } + } + + while(*b == '{') { + if ((e = switch_find_end_paren(b, '{', '}'))) { + b = e + 1; + while(*b == ' ') b++; + } + } + + return strcmp(a, b); +} + static inline const char *switch_parse_audio_col(switch_audio_col_t col) { @@ -1487,6 +1503,9 @@ SWITCH_DECLARE(unsigned long) switch_getpid(void); SWITCH_DECLARE(switch_status_t) switch_digest(const char *digest_name, unsigned char **digest, const void *input, switch_size_t inputLen, unsigned int *outputlen); SWITCH_DECLARE(switch_status_t) switch_digest_string(const char *digest_name, char **digest_str, const void *input, switch_size_t inputLen, unsigned int *outputlen); +SWITCH_DECLARE(char *) switch_must_strdup(const char *_s); +SWITCH_DECLARE(const char *) switch_memory_usage_stream(switch_stream_handle_t *stream); + SWITCH_END_EXTERN_C #endif /* For Emacs: diff --git a/src/include/switch_xml.h b/src/include/switch_xml.h index fab9d981ef..9a308813a7 100644 --- a/src/include/switch_xml.h +++ b/src/include/switch_xml.h @@ -102,6 +102,10 @@ struct switch_xml { /*! is_switch_xml_root bool */ switch_bool_t is_switch_xml_root_t; uint32_t refs; + /*! pointer to end of opening tag, '>', in the original parsed text */ + const char *open; + /*! pointer to start of closing tag, '<', in the original parsed text */ + const char *close; }; /*! diff --git a/src/include/test/switch_fct.h b/src/include/test/switch_fct.h index f88821b49c..8cb07cc20f 100644 --- a/src/include/test/switch_fct.h +++ b/src/include/test/switch_fct.h @@ -2858,6 +2858,10 @@ fct_standard_logger__on_chk( /* Only record failures. */ if ( !fctchk__is_pass(e->chk) ) { + printf("\nTEST FAIL: %s(%d): %s\n", + fctchk__file(e->chk), + fctchk__lineno(e->chk), + fctchk__msg(e->chk)); fct_logger_record_failure(e->chk, &(logger->failed_cndtns_list)); } } diff --git a/src/include/test/switch_test.h b/src/include/test/switch_test.h index 3413884145..db5f4f7a7d 100644 --- a/src/include/test/switch_test.h +++ b/src/include/test/switch_test.h @@ -203,13 +203,13 @@ static switch_status_t fst_init_core_and_modload(const char *confdir, const char * Check a test /w error message */ #define fst_xcheck(expr, error_msg) \ - fct_xchk(expr, "%s", error_msg); + (fct_xchk(expr, "%s", error_msg)) /** * Fail a test */ #define fst_fail(error_msg) \ - fct_xchk(0, "%s", error_msg); + (fct_xchk(0, "%s", error_msg)) /** * Check duration relative to test start, last marked time, or last check. @@ -236,7 +236,7 @@ static switch_status_t fst_init_core_and_modload(const char *confdir, const char (actual), \ (expected), \ (precision) \ - ); + ) /** * Check if double-precision number is in range @@ -248,7 +248,7 @@ static switch_status_t fst_init_core_and_modload(const char *confdir, const char (actual), \ (expected), \ (precision) \ - ); + ) /** * Run test without loading FS core @@ -484,9 +484,10 @@ static switch_status_t fst_init_core_and_modload(const char *confdir, const char * * @param name the name of this test * @param rate the rate of the channel + * @param video_codec the rate of the channel */ -#define FST_SESSION_BEGIN_RATE(name, rate) \ +#define FST_SESSION_BEGIN_RATE_VIDEO(name, rate, video_codec) \ FCT_TEST_BGN(name) \ { \ if (fst_core) { \ @@ -513,7 +514,7 @@ static switch_status_t fst_init_core_and_modload(const char *confdir, const char fst_requires(switch_event_create_plain(&fst_originate_vars, SWITCH_EVENT_CHANNEL_DATA) == SWITCH_STATUS_SUCCESS); \ switch_event_add_header_string(fst_originate_vars, SWITCH_STACK_BOTTOM, "origination_caller_id_number", "+15551112222"); \ switch_event_add_header(fst_originate_vars, SWITCH_STACK_BOTTOM, "rate", "%d", rate); \ - if (switch_ivr_originate(NULL, &fst_session, &fst_cause, "null/+15553334444", 2, NULL, NULL, NULL, NULL, fst_originate_vars, SOF_NONE, NULL, NULL) == SWITCH_STATUS_SUCCESS && fst_session) { \ + if (switch_ivr_originate(NULL, &fst_session, &fst_cause, "{null_video_codec=" video_codec "}null/+15553334444", 2, NULL, NULL, NULL, NULL, fst_originate_vars, SOF_NONE, NULL, NULL) == SWITCH_STATUS_SUCCESS && fst_session) { \ switch_memory_pool_t *fst_session_pool = switch_core_session_get_pool(fst_session); \ switch_channel_t *fst_channel = switch_core_session_get_channel(fst_session); \ switch_channel_set_state(fst_channel, CS_SOFT_EXECUTE); \ @@ -521,14 +522,16 @@ static switch_status_t fst_init_core_and_modload(const char *confdir, const char switch_channel_set_variable(fst_channel, "send_silence_when_idle", "-1"); \ switch_channel_set_variable(fst_channel, "RECORD_STEREO", "true"); \ switch_ivr_record_session(fst_session, (char *)"/tmp/"#name".wav", 0, NULL); \ + switch_channel_set_variable(fst_channel, "RECORD_STEREO", NULL); \ for(;;) { /** * Define a session test in a test suite. This can be used to test IVR functions. - * See FST_SESSION_BEGIN_RATE + * See FST_SESSION_BEGIN_RATE_VIDEO */ #define FST_SESSION_BEGIN(name) FST_SESSION_BEGIN_RATE(name, 8000) +#define FST_SESSION_BEGIN_RATE(name, rate) FST_SESSION_BEGIN_RATE_VIDEO(name, rate, "") /* BODY OF TEST CASE HERE */ diff --git a/src/mod/applications/mod_av/.gitignore b/src/mod/applications/mod_av/.gitignore new file mode 100644 index 0000000000..35829e418c --- /dev/null +++ b/src/mod/applications/mod_av/.gitignore @@ -0,0 +1,3 @@ +test/test_BT7.mp4 +test/test_RGB.mp4 +test/test_packetizer diff --git a/src/mod/applications/mod_av/avcodec.c b/src/mod/applications/mod_av/avcodec.c index 01c862cf11..703dc1b2ce 100644 --- a/src/mod/applications/mod_av/avcodec.c +++ b/src/mod/applications/mod_av/avcodec.c @@ -385,6 +385,7 @@ typedef struct h264_codec_context_s { switch_image_t *img; switch_image_t *encimg; int need_key_frame; + switch_time_t last_keyframe_request; switch_bool_t nalu_28_start; int change_bandwidth; @@ -420,7 +421,7 @@ struct avcodec_globals { int debug; uint32_t max_bitrate; uint32_t rtp_slice_size; - uint32_t key_frame_min_freq; + uint32_t key_frame_min_freq; // in ms uint32_t enc_threads; uint32_t dec_threads; @@ -1567,10 +1568,14 @@ static switch_status_t switch_h264_encode(switch_codec_t *codec, switch_frame_t avframe->pts = context->pts++; - if (context->need_key_frame) { - switch_log_printf(SWITCH_CHANNEL_LOG, SWITCH_LOG_DEBUG5, "Send AV KEYFRAME\n"); + if (context->need_key_frame && (context->last_keyframe_request + avcodec_globals.key_frame_min_freq) < switch_time_now()) { + if (avcodec_globals.debug) { + switch_log_printf(SWITCH_CHANNEL_LOG, SWITCH_LOG_NOTICE, "Generate/Send AV KEYFRAME\n"); + } + avframe->pict_type = AV_PICTURE_TYPE_I; avframe->key_frame = 1; + context->last_keyframe_request = switch_time_now(); } /* encode the image */ @@ -1585,7 +1590,7 @@ GCC_DIAG_ON(deprecated-declarations) goto error; } - if (context->need_key_frame) { + if (context->need_key_frame && avframe->key_frame == 1) { avframe->pict_type = 0; avframe->key_frame = 0; context->need_key_frame = 0; @@ -1633,8 +1638,12 @@ GCC_DIAG_ON(deprecated-declarations) context->nalus[i].start = p; context->nalus[i].eat = p; - if (mod_av_globals.debug && (*p & 0x1f) == 7) { - switch_log_printf(SWITCH_CHANNEL_LOG, SWITCH_LOG_NOTICE, "KEY FRAME GENERATED\n"); + if ((*p & 0x1f) == 7) { // Got Keyframe + // prevent to generate key frame too frequently + context->last_keyframe_request = switch_time_now(); + if (mod_av_globals.debug) { + switch_log_printf(SWITCH_CHANNEL_LOG, SWITCH_LOG_NOTICE, "KEY FRAME GENERATED\n"); + } } } else { context->nalus[i].len = p - context->nalus[i].start; @@ -1764,6 +1773,12 @@ static switch_status_t switch_h264_control(switch_codec_t *codec, h264_codec_context_t *context = (h264_codec_context_t *)codec->private_info; switch(cmd) { + case SCC_DEBUG: + { + int32_t level = *((uint32_t *) cmd_data); + mod_av_globals.debug = level; + } + break; case SCC_VIDEO_GEN_KEYFRAME: context->need_key_frame = 1; break; @@ -1964,6 +1979,9 @@ static void parse_profile(avcodec_profile_t *aprofile, switch_xml_t profile) ctx = &aprofile->ctx; + ctx->profile = FF_PROFILE_H264_BASELINE; + ctx->level = 31; + for (param = switch_xml_child(profile, "param"); param; param = param->next) { const char *name = switch_xml_attr(param, "name"); const char *value = switch_xml_attr(param, "value"); @@ -1975,9 +1993,6 @@ static void parse_profile(avcodec_profile_t *aprofile, switch_xml_t profile) val = atoi(value); - ctx->profile = FF_PROFILE_H264_BASELINE; - ctx->level = 31; - if (!strcmp(name, "dec-threads")) { aprofile->decoder_thread_count = switch_parse_cpu_string(value); } else if (!strcmp(name, "enc-threads")) { diff --git a/src/mod/applications/mod_av/avformat.c b/src/mod/applications/mod_av/avformat.c index d45f584b2d..f748968202 100644 --- a/src/mod/applications/mod_av/avformat.c +++ b/src/mod/applications/mod_av/avformat.c @@ -54,6 +54,8 @@ GCC_DIAG_OFF(deprecated-declarations) #include #endif +#define SLICE_SIZE (SWITCH_DEFAULT_VIDEO_SIZE + 100) + GCC_DIAG_ON(deprecated-declarations) #define SCALE_FLAGS SWS_BICUBIC #define DFT_RECORD_OFFSET 0 @@ -116,8 +118,6 @@ typedef struct record_helper_s { uint64_t last_ts; } record_helper_t; - - /* file interface */ struct av_file_context { @@ -161,6 +161,11 @@ struct av_file_context { switch_time_t last_vid_write; int audio_timer; + + switch_bool_t no_video_decode; + switch_queue_t *video_pkt_queue; + switch_packetizer_t *packetizer; + AVPacket *last_read_pkt; }; typedef struct av_file_context av_file_context_t; @@ -337,12 +342,27 @@ static void log_packet(const AVFormatContext *fmt_ctx, const AVPacket *pkt) } } +static int interrupt_cb(void *cp) +{ + av_file_context_t *context = (av_file_context_t *) cp; + + if (context->closed) { + return 1; + } + + return 0; +} + + static int mod_avformat_alloc_output_context2(AVFormatContext **avctx, AVOutputFormat *oformat, - const char *format, const char *filename) + const char *format, const char *filename, av_file_context_t *context) { AVFormatContext *s = avformat_alloc_context(); int ret = 0; + s->interrupt_callback.callback = interrupt_cb; + s->interrupt_callback.opaque = context; + *avctx = NULL; if (!s) goto nomem; @@ -772,6 +792,16 @@ static int flush_video_queue(switch_queue_t *q, int min) return switch_queue_size(q); } +static void flush_video_pkt_queue(switch_queue_t *q) +{ + AVPacket *pkt; + + while (switch_queue_trypop(q, (void **)&pkt) == SWITCH_STATUS_SUCCESS) { + av_packet_unref(pkt); + free(pkt); + } +} + static void *SWITCH_THREAD_FUNC video_thread_run(switch_thread_t *thread, void *obj) { av_file_context_t *context = (av_file_context_t *) obj; @@ -792,7 +822,12 @@ static void *SWITCH_THREAD_FUNC video_thread_run(switch_thread_t *thread, void * top: switch_assert(context->eh.video_queue); - + while(switch_queue_size(context->eh.video_queue) > 1) { + switch_image_t *tmp_img; + switch_queue_pop(context->eh.video_queue, &pop); + tmp_img = (switch_image_t *) pop; + switch_img_free(&tmp_img); + } if (switch_queue_pop(context->eh.video_queue, &pop) == SWITCH_STATUS_SUCCESS) { switch_img_free(&img); @@ -880,7 +915,7 @@ static void *SWITCH_THREAD_FUNC video_thread_run(switch_thread_t *thread, void * } else { uint64_t delta_tmp; - switch_core_timer_sync(context->eh.video_timer); + switch_core_timer_next(context->eh.video_timer); delta_tmp = (context->eh.video_timer->samplecount * 90) - context->eh.last_ts; if (delta_tmp != 0) { @@ -1107,23 +1142,38 @@ static switch_status_t open_input_file(av_file_context_t *context, switch_file_h int error; int i, idx = 0; switch_status_t status = SWITCH_STATUS_SUCCESS; - + // av_dict_set(&opts, "c:v", "libvpx", 0); /** Open the input file to read from it. */ - if ((error = avformat_open_input(&context->fc, filename, NULL, NULL)) < 0) { - char ebuf[255] = ""; - switch_log_printf(SWITCH_CHANNEL_LOG, SWITCH_LOG_WARNING, "Could not open input file '%s' (error '%s')\n", filename, get_error_text(error, ebuf, sizeof(ebuf))); + + if (!context->fc) { + context->fc = avformat_alloc_context(); + } + + if (!context->fc) { + switch_log_printf(SWITCH_CHANNEL_LOG, SWITCH_LOG_ERROR, "Could not open input file '%s' (error '%s')\n", filename, "NO MEM"); switch_goto_status(SWITCH_STATUS_FALSE, err); } + context->fc->interrupt_callback.callback = interrupt_cb; + context->fc->interrupt_callback.opaque = context; + + if ((error = avformat_open_input(&context->fc, filename, NULL, NULL)) < 0) { + char ebuf[255] = ""; + switch_log_printf(SWITCH_CHANNEL_LOG, SWITCH_LOG_WARNING, "Could not open input file '%s' (error '%s')\n", filename, get_error_text(error, ebuf, sizeof(ebuf))); + avformat_free_context(context->fc); + context->fc = NULL; + switch_goto_status(SWITCH_STATUS_FALSE, err); + } + handle->seekable = context->fc->iformat->read_seek2 ? 1 : (context->fc->iformat->read_seek ? 1 : 0); switch_log_printf(SWITCH_CHANNEL_LOG, SWITCH_LOG_INFO, "file %s is %sseekable\n", filename, handle->seekable ? "" : "not "); /** Get information on the input file (number of streams etc.). */ if ((error = avformat_find_stream_info(context->fc, opts ? &opts : NULL)) < 0) { char ebuf[255] = ""; - switch_log_printf(SWITCH_CHANNEL_LOG, SWITCH_LOG_WARNING, "Could not open find stream info (error '%s')\n", get_error_text(error, ebuf, sizeof(ebuf))); + switch_log_printf(SWITCH_CHANNEL_LOG, SWITCH_LOG_WARNING, "Could not find stream info in file: %s, error = %s)\n", filename, get_error_text(error, ebuf, sizeof(ebuf))); if (opts) av_dict_free(&opts); switch_goto_status(SWITCH_STATUS_FALSE, err); } @@ -1145,6 +1195,11 @@ GCC_DIAG_ON(deprecated-declarations) handle->duration = av_rescale_q(context->video_st.st->duration != AV_NOPTS_VALUE ? context->video_st.st->duration : context->fc->duration / AV_TIME_BASE * 1000, context->video_st.st->time_base, AV_TIME_BASE_Q); } + + if (context->fc->bit_rate) { + handle->mm.source_kps = context->fc->bit_rate / 1024; + } + if (context->video_st.st->avg_frame_rate.num) { handle->mm.source_fps = ceil(av_q2d(context->video_st.st->avg_frame_rate)); } else { @@ -1289,12 +1344,21 @@ GCC_DIAG_ON(deprecated-declarations) return status; err: - /* - if (context->has_video) close_stream(context->fc, &context->video_st); - if (context->has_audio) close_stream(context->fc, &context->audio_st); + if (context->fc) { + int nb_streams = context->fc->nb_streams; + + if (nb_streams > 2) nb_streams = 2; + + if (context->has_video) close_stream(context->fc, &context->video_st); + + for (i = 0; i < nb_streams; i++) { + close_stream(context->fc, &context->audio_st[i]); + } + + avformat_free_context(context->fc); + context->fc = NULL; + } - if (context->fc) avformat_close_input(&context->fc); - */ return status; } @@ -1309,7 +1373,7 @@ static void *SWITCH_THREAD_FUNC file_read_thread_run(switch_thread_t *thread, vo int error; int sync = 0; int eof = 0; - + switch_mutex_lock(context->mutex); context->file_read_thread_started = 1; context->file_read_thread_running = 1; @@ -1379,7 +1443,7 @@ GCC_DIAG_ON(deprecated-declarations) } else { char ebuf[255] = ""; switch_log_printf(SWITCH_CHANNEL_LOG, SWITCH_LOG_WARNING, "Could not read frame (error '%s')\n", get_error_text(error, ebuf, sizeof(ebuf))); - break; + continue; } } @@ -1387,6 +1451,34 @@ GCC_DIAG_ON(deprecated-declarations) if (context->has_video && pkt.stream_index == context->video_st.st->index) { AVFrame *vframe; switch_image_t *img; + + if (context->no_video_decode) { + if (eof) { + break; + } else { + switch_status_t status; + AVPacket *new_pkt = malloc(sizeof(AVPacket)); + + if (0) { // debug + uint8_t *p = pkt.data; + switch_log_printf(SWITCH_CHANNEL_LOG, SWITCH_LOG_ERROR, "size = %u %x %x %x %x %x %x\n", pkt.size, *p, *(p+1), *(p+2), *(p+3), *(p+4), *(p+5)); + } + + av_init_packet(new_pkt); + av_packet_ref(new_pkt, &pkt); + status = switch_queue_push(context->video_pkt_queue, new_pkt); + // switch_log_printf(SWITCH_CHANNEL_LOG, SWITCH_LOG_ERROR, "size = %4u flag=%x pts=%" SWITCH_INT64_T_FMT " dts=%" SWITCH_INT64_T_FMT "\n", pkt.size, pkt.flags, pkt.pts, pkt.dts); + + context->vid_ready = 1; + if (status != SWITCH_STATUS_SUCCESS) { + av_packet_unref(new_pkt); + free(new_pkt); + } + av_packet_unref(&pkt); + continue; + } + } + if (!sync) { switch_buffer_zero(context->audio_buffer); sync = 1; @@ -1403,7 +1495,7 @@ GCC_DIAG_ON(deprecated-declarations) switch_log_printf(SWITCH_CHANNEL_LOG, SWITCH_LOG_WARNING, "Could not decode frame (error '%s')\n", get_error_text(error, ebuf, sizeof(ebuf))); av_packet_unref(&pkt); av_frame_free(&vframe); - break; + continue; } // switch_log_printf(SWITCH_CHANNEL_LOG, SWITCH_LOG_ERROR, "pkt: %d, pts: %lld dts: %lld\n", pkt.size, pkt.pts, pkt.dts); @@ -1499,9 +1591,6 @@ GCC_DIAG_ON(deprecated-declarations) context->vid_ready = 1; switch_queue_push(context->eh.video_queue, img); context->last_vid_push = switch_time_now(); - - - } } } @@ -1523,9 +1612,9 @@ GCC_DIAG_OFF(deprecated-declarations) if ((error = avcodec_decode_audio4(context->audio_st[0].st->codec, &in_frame, &got_data, &pkt)) < 0) { GCC_DIAG_ON(deprecated-declarations) char ebuf[255] = ""; - switch_log_printf(SWITCH_CHANNEL_LOG, SWITCH_LOG_WARNING, "Could not decode frame (error '%s')\n", get_error_text(error, ebuf, sizeof(ebuf))); + switch_log_printf(SWITCH_CHANNEL_LOG, SWITCH_LOG_WARNING, "Could not decode frame (error '%s')\n", get_error_text(error, ebuf, sizeof(ebuf))); av_packet_unref(&pkt); - break; + continue; } // switch_log_printf(SWITCH_CHANNEL_LOG, SWITCH_LOG_ERROR, "pkt: %d, decodedddd: %d pts: %lld dts: %lld\n", pkt.size, error, pkt.pts, pkt.dts); @@ -1601,23 +1690,33 @@ static switch_status_t av_file_open(switch_file_handle_t *handle, const char *pa disable_write_buffer = 1; } - if ((ext = strrchr((char *)path, '.')) == 0) { - switch_log_printf(SWITCH_CHANNEL_LOG, SWITCH_LOG_ERROR, "Invalid Format\n"); - return SWITCH_STATUS_GENERR; - } else if (handle->stream_name && (!strcasecmp(handle->stream_name, "rtmp") || !strcasecmp(handle->stream_name, "youtube"))) { + if (handle->stream_name && (!strcasecmp(handle->stream_name, "rtmp") || !strcasecmp(handle->stream_name, "rtmps") || !strcasecmp(handle->stream_name, "youtube"))) { + char *secure = ""; + format = "flv"; + if ((ext = strrchr((char *)path, '.')) == 0) { + ext = ".flv"; + } + + if (!strcasecmp(handle->stream_name, "rtmps")) secure = "s"; // meh really silly format for the user / pass libav..... if (handle->mm.auth_username && handle->mm.auth_password) { - switch_snprintf(file, sizeof(file), "rtmp://%s pubUser=%s pubPasswd=%s flashver=FMLE/3.0", path, handle->mm.auth_username, handle->mm.auth_password); + switch_snprintf(file, sizeof(file), "rtmp%s://%s pubUser=%s pubPasswd=%s flashver=FMLE/3.0", secure, path, handle->mm.auth_username, handle->mm.auth_password); } else { - switch_snprintf(file, sizeof(file), "rtmp://%s", path); + switch_snprintf(file, sizeof(file), "rtmp%s://%s", secure, path); } } else if (handle->stream_name && !strcasecmp(handle->stream_name, "rtsp")) { format = "rtsp"; + if ((ext = strrchr((char *)path, '.')) == 0) { + ext = ".rtsp"; + } switch_snprintf(file, sizeof(file), "rtsp://%s", path); disable_write_buffer = 1; + } else if ((ext = strrchr((char *)path, '.')) == 0) { + switch_log_printf(SWITCH_CHANNEL_LOG, SWITCH_LOG_ERROR, "Invalid Format\n"); + return SWITCH_STATUS_GENERR; } @@ -1673,9 +1772,16 @@ static switch_status_t av_file_open(switch_file_handle_t *handle, const char *pa } if (context->has_video) { + switch_fps_t fps_data = { 0 }; switch_queue_create(&context->eh.video_queue, context->read_fps, handle->memory_pool); + context->no_video_decode = handle->params && switch_true(switch_event_get_header(handle->params, "no_video_decode")); + if (context->no_video_decode) { + switch_log_printf(SWITCH_CHANNEL_LOG, SWITCH_LOG_INFO, "Opening video in no decode mode\n"); + switch_queue_create(&context->video_pkt_queue, 120 * 5, handle->memory_pool); + } switch_mutex_init(&context->eh.mutex, SWITCH_MUTEX_NESTED, handle->memory_pool); - switch_core_timer_init(&context->video_timer, "soft", (int)(1000.0f / context->read_fps), 1, context->pool); + switch_calc_video_fps(&fps_data, context->read_fps); + switch_core_timer_init(&context->video_timer, "soft", fps_data.ms, fps_data.samples, context->pool); } { @@ -1689,7 +1795,7 @@ static switch_status_t av_file_open(switch_file_handle_t *handle, const char *pa return SWITCH_STATUS_SUCCESS; } - mod_avformat_alloc_output_context2(&context->fc, NULL, format, (char *)file); + mod_avformat_alloc_output_context2(&context->fc, NULL, format, (char *)file, context); if (!context->fc) { switch_log_printf(SWITCH_CHANNEL_LOG, SWITCH_LOG_WARNING, "Could not deduce output format from file extension\n"); @@ -1761,7 +1867,7 @@ static switch_status_t av_file_open(switch_file_handle_t *handle, const char *pa if (switch_test_flag(handle, SWITCH_FILE_FLAG_VIDEO) && fmt->video_codec != AV_CODEC_ID_NONE) { const AVCodecDescriptor *desc; - if ((handle->stream_name && (!strcasecmp(handle->stream_name, "rtmp") || !strcasecmp(handle->stream_name, "youtube")))) { + if ((handle->stream_name && (!strcasecmp(handle->stream_name, "rtmp") || !strcasecmp(handle->stream_name, "rtmps") || !strcasecmp(handle->stream_name, "youtube")))) { if (fmt->video_codec != AV_CODEC_ID_H264 ) { fmt->video_codec = AV_CODEC_ID_H264; // force H264 @@ -2171,6 +2277,15 @@ static switch_status_t av_file_close(switch_file_handle_t *handle) context->file_read_thread_running = 0; } + if (context->video_pkt_queue) { + flush_video_pkt_queue(context->video_pkt_queue); + switch_queue_term(context->video_pkt_queue); + } + + if (context->packetizer) { + switch_packetizer_close(&context->packetizer); + } + if (context->file_read_thread) { switch_thread_join(&status, context->file_read_thread); context->file_read_thread = NULL; @@ -2243,6 +2358,7 @@ static switch_status_t av_file_read(switch_file_handle_t *handle, void *data, si } switch_mutex_lock(context->mutex); + while (!context->file_read_thread_started) { switch_thread_cond_wait(context->cond, context->mutex); } @@ -2328,6 +2444,82 @@ static switch_status_t av_file_read_video(switch_file_handle_t *handle, switch_f } #else +static switch_status_t no_video_decode_packets(switch_file_handle_t *handle, switch_frame_t *frame, switch_video_read_flag_t flags) +{ + av_file_context_t *context = (av_file_context_t *)handle->private_info; + MediaStream *mst = &context->video_st; + AVStream *st = mst->st; + // AVCodecContext *ctx = st->codec; + // int ticks = 0; + // int64_t max_delta = 1 * AV_TIME_BASE; // 1 second + switch_status_t status = SWITCH_STATUS_SUCCESS; + AVPacket *pkt; + int64_t pts; + + + if (!context->packetizer) { + // uint8_t *p = st->codecpar->extradata; + // switch_log_printf(SWITCH_CHANNEL_LOG, SWITCH_LOG_ERROR, "size = %u %x %x %x %x %x %x\n", st->codecpar->extradata_size, *p, *(p+1), *(p+2), *(p+3), *(p+4), *(p+5)); + + context->packetizer = switch_packetizer_create(SPT_H264_SIZED_BITSTREAM, SLICE_SIZE); + if (!context->packetizer) return SWITCH_STATUS_FALSE; + + switch_packetizer_feed_extradata(context->packetizer, st->codecpar->extradata, st->codecpar->extradata_size); + } + + if (context->last_read_pkt) { + status = switch_packetizer_read(context->packetizer, frame); + if (status == SWITCH_STATUS_SUCCESS) { + av_packet_unref(context->last_read_pkt); + free(context->last_read_pkt); + context->last_read_pkt = NULL; + } + return status; + } + + status = switch_queue_trypop(context->video_pkt_queue, (void **)&pkt); + + if (status != SWITCH_STATUS_SUCCESS || !pkt) { + switch_cond_next(); + return SWITCH_STATUS_BREAK; + } + + context->last_read_pkt = pkt; + switch_packetizer_feed(context->packetizer, pkt->data, pkt->size); + status = switch_packetizer_read(context->packetizer, frame); + pts = av_rescale_q(pkt->pts, st->time_base, AV_TIME_BASE_Q); + frame->timestamp = pts * 9 / 100; // scale to sample 900000 + // switch_log_printf(SWITCH_CHANNEL_LOG, SWITCH_LOG_INFO, "pts=%" SWITCH_INT64_T_FMT " status = %d\n", pts, status); + + if (status == SWITCH_STATUS_SUCCESS) { + av_packet_unref(context->last_read_pkt); + free(context->last_read_pkt); + context->last_read_pkt = NULL; + } + + + if (status == SWITCH_STATUS_SUCCESS || status == SWITCH_STATUS_MORE_DATA) { + if (!context->video_start_time) { + context->video_start_time = switch_time_now() - pts; + switch_log_printf(SWITCH_CHANNEL_LOG, SWITCH_LOG_DEBUG, "set start time: %" SWITCH_INT64_T_FMT " now: %" SWITCH_INT64_T_FMT " pts: %" SWITCH_INT64_T_FMT "\n", context->video_start_time, switch_time_now(), pts); + } else if (flags & SVR_BLOCK) { + int64_t sleep = pts - (switch_time_now() - context->video_start_time); + if (sleep > 0) { + // switch_log_printf(SWITCH_CHANNEL_LOG, SWITCH_LOG_DEBUG, "zzZ... %" SWITCH_INT64_T_FMT "\n", sleep); + if (sleep > 1000000) { + sleep = 1000000; + switch_log_printf(SWITCH_CHANNEL_LOG, SWITCH_LOG_DEBUG, "but zzZ... %" SWITCH_INT64_T_FMT " at most\n", sleep); + } + switch_yield(sleep); + } else { + switch_log_printf(SWITCH_CHANNEL_LOG, SWITCH_LOG_WARNING, "video is late %" SWITCH_INT64_T_FMT "\n", sleep); + } + } + } + + return status; +} + static switch_status_t av_file_read_video(switch_file_handle_t *handle, switch_frame_t *frame, switch_video_read_flag_t flags) { av_file_context_t *context = (av_file_context_t *)handle->private_info; @@ -2347,6 +2539,13 @@ static switch_status_t av_file_read_video(switch_file_handle_t *handle, switch_f return SWITCH_STATUS_BREAK; } + if (context->no_video_decode) { + switch_set_flag(frame, SFF_ENCODED); + status = no_video_decode_packets(handle, frame, flags); + // switch_log_printf(SWITCH_CHANNEL_LOG, SWITCH_LOG_ERROR, "return len=%4u nalu=%02x m=%d ts=%u\n", frame->datalen, *(uint8_t *)frame->data, frame->m, frame->timestamp); + return status; + } + if (handle->mm.fps > 0 && handle->mm.fps < smaller_ts) { smaller_ts = handle->mm.fps; } @@ -2434,6 +2633,7 @@ static switch_status_t av_file_read_video(switch_file_handle_t *handle, switch_f context->vid_ready = 1; return SWITCH_STATUS_SUCCESS; } + return SWITCH_STATUS_BREAK; } } @@ -2703,6 +2903,7 @@ SWITCH_MODULE_LOAD_FUNCTION(mod_avformat_load) supported_formats[i++] = "av"; supported_formats[i++] = "rtmp"; + supported_formats[i++] = "rtmps"; supported_formats[i++] = "rtsp"; supported_formats[i++] = "mp4"; supported_formats[i++] = "m4a"; diff --git a/src/mod/applications/mod_av/mod_av.c b/src/mod/applications/mod_av/mod_av.c index 4716b60804..5d93d9adc7 100644 --- a/src/mod/applications/mod_av/mod_av.c +++ b/src/mod/applications/mod_av/mod_av.c @@ -119,7 +119,21 @@ static void log_callback(void *ptr, int level, const char *fmt, va_list vl) } // switch_level = SWITCH_LOG_ERROR; // hardcoded for debug - switch_log_vprintf(SWITCH_CHANNEL_LOG_CLEAN, switch_level, fmt, vl); + if (mod_av_globals.debug < 7) { + switch_log_vprintf(SWITCH_CHANNEL_LOG_CLEAN, switch_level, fmt, vl); + } else { + char buffer[1024] = {0}; + char *s = NULL; + vsprintf(buffer, fmt, vl); + s = strstr(buffer, "nal_unit_type"); + if (!zstr(s) && *(s+15) == '7') { + switch_log_printf(SWITCH_CHANNEL_LOG, switch_level, "Read SPS\n"); + } else if (!zstr(s) && *(s+15) == '8') { + switch_log_printf(SWITCH_CHANNEL_LOG, switch_level, "Read PPS\n"); + } else if (!zstr(s) && *(s+15) == '5') { + switch_log_printf(SWITCH_CHANNEL_LOG, switch_level, "Read I-frame\n"); + } + } } diff --git a/src/mod/applications/mod_av/test/test_avformat.c b/src/mod/applications/mod_av/test/test_avformat.c index af364afd66..5a0043e6cc 100644 --- a/src/mod/applications/mod_av/test/test_avformat.c +++ b/src/mod/applications/mod_av/test/test_avformat.c @@ -162,6 +162,94 @@ FST_CORE_BEGIN("conf") } FST_TEST_END() + FST_TEST_BEGIN(avformat_test_play_no_decode) + { + char path[1024]; + switch_status_t status; + switch_file_handle_t fh = { 0 }; + uint8_t data[SWITCH_RECOMMENDED_BUFFER_SIZE] = { 0 }; + switch_frame_t frame = { 0 }; + switch_size_t len = SAMPLES; + uint32_t flags = SWITCH_FILE_FLAG_READ | SWITCH_FILE_DATA_SHORT | SWITCH_FILE_FLAG_VIDEO; + int i = 0; + + sprintf(path, "{no_video_decode=true}%s%s%s", SWITCH_GLOBAL_dirs.conf_dir, SWITCH_PATH_SEPARATOR, "../test_RGB.mp4"); + // switch_set_string(path, "{no_video_decode=true}/usr/local/freeswitch/storage/bingbing.mp4"); + status = switch_core_file_open(&fh, path, 1, 8000, flags, fst_pool); + fst_requires(status == SWITCH_STATUS_SUCCESS); + fst_requires(switch_test_flag(&fh, SWITCH_FILE_OPEN)); + frame.packet = data; + frame.data = data + 12; + frame.buflen = SWITCH_RECOMMENDED_BUFFER_SIZE; + + do { + frame.datalen = SWITCH_RECOMMENDED_BUFFER_SIZE - 12; + status = switch_core_file_read(&fh, data, &len); + switch_log_printf(SWITCH_CHANNEL_LOG, SWITCH_LOG_INFO, "status: %d len: %d\n", status, (int)len); + fst_check(frame.img == NULL); + frame.datalen = SWITCH_RECOMMENDED_BUFFER_SIZE - 12; + status = switch_core_file_read_video(&fh, &frame, 0); + fst_check(frame.img == NULL); + switch_log_printf(SWITCH_CHANNEL_LOG, SWITCH_LOG_NOTICE, "status: %d len: %d %02x\n", status, frame.datalen, *(uint8_t *)frame.data); + } while (status == SWITCH_STATUS_MORE_DATA); + + switch_core_file_close(&fh); + } + FST_TEST_END() + + FST_TEST_BEGIN(avformat_test_read_err) + { + char *path = "$$-non-exist-file.mp4"; + switch_status_t status; + switch_file_handle_t fh = { 0 }; + uint32_t flags = SWITCH_FILE_FLAG_READ | SWITCH_FILE_DATA_SHORT | SWITCH_FILE_FLAG_VIDEO; + + status = switch_core_file_open(&fh, path, 1, 8000, flags, fst_pool); + fst_check(status == SWITCH_STATUS_GENERR); + } + FST_TEST_END() + + FST_TEST_BEGIN(avformat_test_read_ok) + { + char path[1024]; + switch_status_t status; + switch_file_handle_t fh = { 0 }; + uint8_t data[SAMPLES * 2] = { 0 }; + switch_frame_t frame = { 0 }; + switch_size_t len = SAMPLES; + uint32_t flags = SWITCH_FILE_FLAG_READ | SWITCH_FILE_DATA_SHORT | SWITCH_FILE_FLAG_VIDEO; + + frame.data = data; + + sprintf(path, "%s%s%s", SWITCH_GLOBAL_dirs.conf_dir, SWITCH_PATH_SEPARATOR, "../test_RGB.mp4"); + status = switch_core_file_open(&fh, path, 1, 8000, flags, fst_pool); + fst_requires(status == SWITCH_STATUS_SUCCESS); + fst_requires(switch_test_flag(&fh, SWITCH_FILE_OPEN)); + + while (1) { + status = switch_core_file_read(&fh, data, &len); + if (status != SWITCH_STATUS_SUCCESS) break; + switch_log_printf(SWITCH_CHANNEL_LOG, SWITCH_LOG_INFO, "read: %" SWITCH_SIZE_T_FMT "\n", len); + // fst_check(len == SAMPLES); + status = switch_core_file_read_video(&fh, &frame, SVR_FLUSH); + + if (status == SWITCH_STATUS_BREAK) { + switch_yield(20000); + continue; + } + + if (status != SWITCH_STATUS_SUCCESS) { + break; + } + + switch_img_free(&frame.img); + switch_yield(20000); + } + + switch_core_file_close(&fh); + } + FST_TEST_END() + FST_TEARDOWN_BEGIN() { //const char *err = NULL; diff --git a/src/mod/applications/mod_av/test/test_mod_av.c b/src/mod/applications/mod_av/test/test_mod_av.c index a058aa63fd..69468dbda2 100644 --- a/src/mod/applications/mod_av/test/test_mod_av.c +++ b/src/mod/applications/mod_av/test/test_mod_av.c @@ -50,7 +50,7 @@ static fctcl_init_t my_cl_options[] = { FST_CORE_BEGIN("conf") { - const char *loop_; + const char *loop_; fctcl_install(my_cl_options); loop_ = fctcl_val("--loop"); @@ -73,7 +73,11 @@ FST_CORE_BEGIN("conf") uint8_t buf[SWITCH_DEFAULT_VIDEO_SIZE + 12]; switch_frame_t frame = { 0 }; int packets = 0; + int frames = 0; + int last_key_frame = 0; + int key_frames = 0; switch_status_t encode_status; + int debug_level = 9; switch_set_string(codec_settings.video.config_profile_name, "conference"); @@ -105,6 +109,8 @@ FST_CORE_BEGIN("conf") frame.timestamp = 0; frame.img = img; + switch_core_codec_control(&codec, SCC_DEBUG, SCCT_NONE, &debug_level, SCCT_INT, NULL, NULL, NULL); + do { frame.datalen = SWITCH_DEFAULT_VIDEO_SIZE; encode_status = switch_core_codec_encode_video(&codec, &frame); @@ -120,8 +126,21 @@ FST_CORE_BEGIN("conf") if (frame.datalen == 0) break; - switch_log_printf(SWITCH_CHANNEL_LOG, SWITCH_LOG_ERROR, "[%d]: %02x %02x | m=%d | %d\n", loop, buf[12], buf[13], frame.m, frame.datalen); + switch_log_printf(SWITCH_CHANNEL_LOG, SWITCH_LOG_INFO, "[%d]: %02x %02x | m=%d | %d\n", frames, buf[12], buf[13], frame.m, frame.datalen); packets++; + + if (frame.m) frames++; + + if (frames % 20 == 2) { + switch_core_codec_control(&codec, SCC_VIDEO_GEN_KEYFRAME, SCCT_NONE, NULL, SCCT_NONE, NULL, NULL, NULL); + } + + if (buf[12] == 0x67) { + key_frames++; + switch_log_printf(SWITCH_CHANNEL_LOG, SWITCH_LOG_NOTICE, "Key Frame %d last=%d diff=%d\n", + key_frames, last_key_frame, frames - last_key_frame); + last_key_frame = frames; + } } } while(encode_status == SWITCH_STATUS_MORE_DATA || loop-- > 1); diff --git a/src/mod/applications/mod_avmd/avmd_amplitude.c b/src/mod/applications/mod_avmd/avmd_amplitude.c index 86523fad4b..e4cd3745e3 100644 --- a/src/mod/applications/mod_avmd/avmd_amplitude.c +++ b/src/mod/applications/mod_avmd/avmd_amplitude.c @@ -2,7 +2,7 @@ * Contributor(s): * * Eric des Courtis - * Piotr Gregor + * Piotr Gregor */ @@ -12,7 +12,7 @@ double avmd_amplitude(circ_buffer_t *b, size_t i, double f) { - double result; - result = sqrt(PSI(b, i) / sin(f * f)); - return result; + double result; + result = sqrt(PSI(b, i) / sin(f * f)); + return result; } diff --git a/src/mod/applications/mod_avmd/avmd_amplitude.h b/src/mod/applications/mod_avmd/avmd_amplitude.h index da98d083e5..1ada729011 100644 --- a/src/mod/applications/mod_avmd/avmd_amplitude.h +++ b/src/mod/applications/mod_avmd/avmd_amplitude.h @@ -4,7 +4,7 @@ * Contributor(s): * * Eric des Courtis - * Piotr Gregor + * Piotr Gregor */ diff --git a/src/mod/applications/mod_avmd/avmd_buffer.c b/src/mod/applications/mod_avmd/avmd_buffer.c index f05f0deb4c..f673a8d31b 100644 --- a/src/mod/applications/mod_avmd/avmd_buffer.c +++ b/src/mod/applications/mod_avmd/avmd_buffer.c @@ -11,20 +11,20 @@ extern size_t next_power_of_2(size_t v) { - size_t prev; - size_t tmp = 1; + size_t prev; + size_t tmp = 1; - v++; + v++; - do { - prev = v; - v &= ~tmp; - tmp <<= 1; - } while (v != 0); + do { + prev = v; + v &= ~tmp; + tmp <<= 1; + } while (v != 0); - prev <<= 1; + prev <<= 1; - return prev; + return prev; } diff --git a/src/mod/applications/mod_avmd/avmd_buffer.h b/src/mod/applications/mod_avmd/avmd_buffer.h index 11d874b5dd..416072caf9 100644 --- a/src/mod/applications/mod_avmd/avmd_buffer.h +++ b/src/mod/applications/mod_avmd/avmd_buffer.h @@ -4,7 +4,7 @@ * Contributor(s): * * Eric des Courtis - * Piotr Gregor + * Piotr Gregor */ @@ -15,89 +15,89 @@ #include #ifdef WIN32 - #include - #include + #include + #include #endif #ifndef INT16_MIN -#define INT16_MIN (-32767-1) +#define INT16_MIN (-32767-1) #endif #ifndef INT16_MAX -#define INT16_MAX (32767) +#define INT16_MAX (32767) #endif #define BUFF_TYPE double typedef struct { - size_t pos; - size_t lpos; - BUFF_TYPE *buf; - size_t buf_len; - size_t mask; - size_t i; - size_t backlog; + size_t pos; + size_t lpos; + BUFF_TYPE *buf; + size_t buf_len; + size_t mask; + size_t i; + size_t backlog; } circ_buffer_t; extern size_t next_power_of_2(size_t v); #define INC_POS(b) \ - { \ + { \ (b)->pos++; \ (b)->pos &= (b)->mask; \ (b)->lpos + 1 < 2 * (b)->buf_len ? (b)->lpos++ : (b)->lpos = (b)->buf_len; \ if ((b)->backlog < (b)->buf_len) (b)->backlog++; \ - } + } #define DEC_POS(b) \ - { \ + { \ (b)->pos--; \ (b)->pos &= (b)->mask; \ (b)->lpos--; \ if (((b)->backlog - 1) < (b)->backlog) (b)->backlog--; \ - } + } #define GET_SAMPLE(b, i) ((b)->buf[(i) & (b)->mask]) #define SET_SAMPLE(b, i, v) ((b)->buf[(i) & (b)->mask] = (v)) #define INSERT_FRAME(b, f, l) \ - do { \ + do { \ for ((b)->i = 0; (b)->i < (l); (b)->i++) { \ - SET_SAMPLE((b), ((b)->i + (b)->pos), (f)[(b)->i]); \ + SET_SAMPLE((b), ((b)->i + (b)->pos), (f)[(b)->i]); \ } \ (b)->pos += (l); \ (b)->lpos += (l); \ (b)->pos %= (b)->buf_len; \ (b)->backlog += (l); \ if ((b)->backlog > (b)->buf_len) (b)->backlog = (b)->buf_len; \ - } while (0) + } while (0) -/* ((f)[(b)->i] >= 0) ? \ - ((BUFF_TYPE)(f)[(b)->i] / (BUFF_TYPE)INT16_MAX): \ - (0.0 - ((BUFF_TYPE)(f)[(b)->i] / (BUFF_TYPE)INT16_MIN)) \ */ +/* ((f)[(b)->i] >= 0) ? \ + ((BUFF_TYPE)(f)[(b)->i] / (BUFF_TYPE)INT16_MAX): \ + (0.0 - ((BUFF_TYPE)(f)[(b)->i] / (BUFF_TYPE)INT16_MIN)) \ */ #define INSERT_INT16_FRAME(b, f, l) \ - { \ + { \ for ((b)->i = 0; (b)->i < (l); (b)->i++) { \ - SET_SAMPLE( \ + SET_SAMPLE( \ (b), \ ((b)->i + (b)->pos), \ ( \ - (BUFF_TYPE)(f)[(b)->i] \ + (BUFF_TYPE)(f)[(b)->i] \ ) \ - ); \ + ); \ } \ (b)->pos += (l); \ (b)->lpos += (l); \ (b)->pos &= (b)->mask; \ (b)->backlog += (l); \ if ((b)->backlog > (b)->buf_len) (b)->backlog = (b)->buf_len; \ - } + } #define CALC_BUFF_LEN(fl, bl) (((fl) >= (bl))? next_power_of_2((fl) << 1): next_power_of_2((bl) << 1)) #define INIT_CIRC_BUFFER(bf, bl, fl, s) \ - { \ + { \ (bf)->buf_len = CALC_BUFF_LEN((fl), (bl)); \ (bf)->mask = (bf)->buf_len - 1; \ (bf)->buf = (BUFF_TYPE *) switch_core_session_alloc(s, (bf)->buf_len * sizeof(BUFF_TYPE)); \ @@ -105,7 +105,7 @@ extern size_t next_power_of_2(size_t v); (bf)->lpos = 0; \ (bf)->backlog = 0; \ (bf)->i = 0; \ - } + } //#define DESTROY_CIRC_BUFFER(b) free((b)->buf) #define GET_BACKLOG_POS(b) ((b)->lpos - (b)->backlog) @@ -114,9 +114,9 @@ extern size_t next_power_of_2(size_t v); #define GET_CURRENT_SAMPLE(b) GET_SAMPLE((b), GET_CURRENT_LPOS((b))) #define ADD_SAMPLE(b, s) \ - do { \ + do { \ INC_POS((b)); \ SET_SAMPLE((b), GET_CURRENT_LPOS((b)), (s)); \ - } while (0) + } while (0) #endif /* __AVMD_BUFFER_H__ */ diff --git a/src/mod/applications/mod_avmd/avmd_desa2.c b/src/mod/applications/mod_avmd/avmd_desa2.c index f6b62785d1..72e347fffd 100644 --- a/src/mod/applications/mod_avmd/avmd_desa2.c +++ b/src/mod/applications/mod_avmd/avmd_desa2.c @@ -2,15 +2,15 @@ * Contributor(s): * * Eric des Courtis - * Piotr Gregor + * Piotr Gregor */ #include #ifdef WIN32 - #include - #define ISNAN(x) (!!(_isnan(x))) - #define ISINF(x) (isinf(x)) + #include + #define ISNAN(x) (!!(_isnan(x))) + #define ISINF(x) (isinf(x)) #endif #include "avmd_buffer.h" @@ -18,50 +18,50 @@ #include "avmd_options.h" #ifdef AVMD_FAST_MATH - #include "avmd_fast_acosf.h" + #include "avmd_fast_acosf.h" #endif double avmd_desa2(circ_buffer_t *b, size_t i, double *amplitude) { - double d; - double n; - double x0; - double x1; - double x2; - double x3; - double x4; - double x2sq; - double result; - double PSI_Xn, PSI_Yn, NEEDED; + double d; + double n; + double x0; + double x1; + double x2; + double x3; + double x4; + double x2sq; + double result; + double PSI_Xn, PSI_Yn, NEEDED; - x0 = GET_SAMPLE((b), (i)); - x1 = GET_SAMPLE((b), ((i) + 1)); - x2 = GET_SAMPLE((b), ((i) + 2)); - x3 = GET_SAMPLE((b), ((i) + 3)); - x4 = GET_SAMPLE((b), ((i) + 4)); + x0 = GET_SAMPLE((b), (i)); + x1 = GET_SAMPLE((b), ((i) + 1)); + x2 = GET_SAMPLE((b), ((i) + 2)); + x3 = GET_SAMPLE((b), ((i) + 3)); + x4 = GET_SAMPLE((b), ((i) + 4)); - x2sq = x2 * x2; - d = 2.0 * ((x2sq) - (x1 * x3)); - if (d == 0.0) { - *amplitude = 0.0; - return 0.0; - } - PSI_Xn = ((x2sq) - (x0 * x4)); - NEEDED = ((x1 * x1) - (x0 * x2)) + ((x3 * x3) - (x2 * x4)); - n = ((x2sq) - (x0 * x4)) - NEEDED; - PSI_Yn = NEEDED + PSI_Xn; + x2sq = x2 * x2; + d = 2.0 * ((x2sq) - (x1 * x3)); + if (d == 0.0) { + *amplitude = 0.0; + return 0.0; + } + PSI_Xn = ((x2sq) - (x0 * x4)); + NEEDED = ((x1 * x1) - (x0 * x2)) + ((x3 * x3) - (x2 * x4)); + n = ((x2sq) - (x0 * x4)) - NEEDED; + PSI_Yn = NEEDED + PSI_Xn; #ifdef AVMD_FAST_MATH - result = 0.5 * (double)fast_acosf((float)n/d); + result = 0.5 * (double)fast_acosf((float)n/d); #else - result = 0.5 * acos(n/d); + result = 0.5 * acos(n/d); #endif - if (ISNAN(result)) { - result = 0.0; - } - *amplitude = 2.0 * PSI_Xn / sqrt(PSI_Yn); + if (ISNAN(result)) { + result = 0.0; + } + *amplitude = 2.0 * PSI_Xn / sqrt(PSI_Yn); - return result; + return result; } diff --git a/src/mod/applications/mod_avmd/avmd_desa2.h b/src/mod/applications/mod_avmd/avmd_desa2.h index 6e8f6e58a7..83541ed38d 100644 --- a/src/mod/applications/mod_avmd/avmd_desa2.h +++ b/src/mod/applications/mod_avmd/avmd_desa2.h @@ -4,7 +4,7 @@ * Contributor(s): * * Eric des Courtis - * Piotr Gregor + * Piotr Gregor */ diff --git a/src/mod/applications/mod_avmd/avmd_desa2_tweaked.c b/src/mod/applications/mod_avmd/avmd_desa2_tweaked.c index a6dab2be28..9aadbb9dac 100644 --- a/src/mod/applications/mod_avmd/avmd_desa2_tweaked.c +++ b/src/mod/applications/mod_avmd/avmd_desa2_tweaked.c @@ -1,71 +1,71 @@ /* * Contributor(s): * - * Piotr Gregor + * Piotr Gregor */ #ifndef __AVMD_DESA2_TWEAKED_H__ - #include "avmd_desa2_tweaked.h" + #include "avmd_desa2_tweaked.h" #endif #include #include #ifdef WIN32 - #include - #define ISNAN(x) (!!(_isnan(x))) - #define ISINF(x) (isinf(x)) + #include + #define ISNAN(x) (!!(_isnan(x))) + #define ISINF(x) (isinf(x)) #endif #include "avmd_buffer.h" #include "avmd_options.h" #ifndef AVMD_FAST_MATH - #include "avmd_fast_acosf.h" + #include "avmd_fast_acosf.h" #endif double avmd_desa2_tweaked(circ_buffer_t *b, size_t i, double *amplitude) { - double n, d; - double x0; - double x1; - double x2; - double x3; - double x4; - double x2sq; - double result; - double PSI_Xn, PSI_Yn, NEEDED; + double n, d; + double x0; + double x1; + double x2; + double x3; + double x4; + double x2sq; + double result; + double PSI_Xn, PSI_Yn, NEEDED; - x0 = GET_SAMPLE((b), (i)); - x1 = GET_SAMPLE((b), ((i) + 1)); - x2 = GET_SAMPLE((b), ((i) + 2)); - x3 = GET_SAMPLE((b), ((i) + 3)); - x4 = GET_SAMPLE((b), ((i) + 4)); - x2sq = x2 * x2; - d = 2.0 * ((x2sq) - (x1 * x3)); - PSI_Xn = ((x2sq) - (x0 * x4)); - NEEDED = ((x1 * x1) - (x0 * x2)) + ((x3 * x3) - (x2 * x4)); - n = ((x2sq) - (x0 * x4)) - NEEDED; - PSI_Yn = NEEDED + PSI_Xn; + x0 = GET_SAMPLE((b), (i)); + x1 = GET_SAMPLE((b), ((i) + 1)); + x2 = GET_SAMPLE((b), ((i) + 2)); + x3 = GET_SAMPLE((b), ((i) + 3)); + x4 = GET_SAMPLE((b), ((i) + 4)); + x2sq = x2 * x2; + d = 2.0 * ((x2sq) - (x1 * x3)); + PSI_Xn = ((x2sq) - (x0 * x4)); + NEEDED = ((x1 * x1) - (x0 * x2)) + ((x3 * x3) - (x2 * x4)); + n = ((x2sq) - (x0 * x4)) - NEEDED; + PSI_Yn = NEEDED + PSI_Xn; /* instead of #ifdef FASTMATH - result = 0.5 * (double)fast_acosf((float)n/d); + result = 0.5 * (double)fast_acosf((float)n/d); #else - result = 0.5 * acos(n/d); + result = 0.5 * acos(n/d); #endif we do simplified, modified for speed version : */ - result = n/d; -/* if (ISINF(result)) { - *amplitude = 0.0; - if (n < 0.0) { - return -10.0; - } else { - return 10.0; - } - }*/ - *amplitude = 2.0 * PSI_Xn / sqrt(PSI_Yn); - return result; + result = n/d; +/* if (ISINF(result)) { + *amplitude = 0.0; + if (n < 0.0) { + return -10.0; + } else { + return 10.0; + } + }*/ + *amplitude = 2.0 * PSI_Xn / sqrt(PSI_Yn); + return result; } diff --git a/src/mod/applications/mod_avmd/avmd_desa2_tweaked.h b/src/mod/applications/mod_avmd/avmd_desa2_tweaked.h index ac6d6fc4d8..38d788cde4 100644 --- a/src/mod/applications/mod_avmd/avmd_desa2_tweaked.h +++ b/src/mod/applications/mod_avmd/avmd_desa2_tweaked.h @@ -10,7 +10,7 @@ * * Contributor(s): * - * Piotr Gregor + * Piotr Gregor * * @date 20 Mar 2016 */ diff --git a/src/mod/applications/mod_avmd/avmd_fast_acosf.c b/src/mod/applications/mod_avmd/avmd_fast_acosf.c index b0d8655d6e..572c6a84f9 100644 --- a/src/mod/applications/mod_avmd/avmd_fast_acosf.c +++ b/src/mod/applications/mod_avmd/avmd_fast_acosf.c @@ -2,7 +2,7 @@ * Contributor(s): * * Eric des Courtis - * Piotr Gregor + * Piotr Gregor */ @@ -14,7 +14,7 @@ #include #ifndef _MSC_VER - #include + #include #endif #include @@ -22,7 +22,7 @@ #include #ifndef _MSC_VER - #include + #include #endif #include @@ -31,7 +31,7 @@ #include #ifndef _MSC_VER - #include + #include #endif #include "avmd_fast_acosf.h" @@ -39,8 +39,8 @@ typedef union { - uint32_t i; - float f; + uint32_t i; + float f; } float_conv_t; /* @@ -58,14 +58,14 @@ typedef union { #define ACOS_TABLE_CONST_EXPONENT_BITS (3) #define ACOS_TABLE_DISCARDED_BITS (3) /* rosolution: - 3: 15 728 640 indices spreading range [0.0, 1.0], table size on disk 134 217 728 bytes (default) - 4: 7 364 320 indices spreading range [0.0, 1.0], table size on disk 67 108 864 bytes - 5: 3 932 160 indices spreading range [0.0, 1.0], table size on disk 33 554 432 bytes - 12: 30 720 indices spreading range [0.0, 1.0], table size on disk 262 144 bytes - 16: 1 920 indices spreading range [0.0, 1.0], table size on disk 16 384 bytes - 20: 120 indices spreading range [0.0, 1.0], table size on disk 1 024 bytes - 24: 7 indices spreading range [0.0, 1.0], table size on disk 64 bytes - 26: 1 indices spreading range [0.0, 1.0], table size on disk 16 bytes + 3: 15 728 640 indices spreading range [0.0, 1.0], table size on disk 134 217 728 bytes (default) + 4: 7 364 320 indices spreading range [0.0, 1.0], table size on disk 67 108 864 bytes + 5: 3 932 160 indices spreading range [0.0, 1.0], table size on disk 33 554 432 bytes + 12: 30 720 indices spreading range [0.0, 1.0], table size on disk 262 144 bytes + 16: 1 920 indices spreading range [0.0, 1.0], table size on disk 16 384 bytes + 20: 120 indices spreading range [0.0, 1.0], table size on disk 1 024 bytes + 24: 7 indices spreading range [0.0, 1.0], table size on disk 64 bytes + 26: 1 indices spreading range [0.0, 1.0], table size on disk 16 bytes */ #define ACOS_TABLE_FREE_EXPONENT_BITS (7 - ACOS_TABLE_CONST_EXPONENT_BITS) #define ACOS_TABLE_DATA_BITS (31 - ACOS_TABLE_CONST_EXPONENT_BITS - ACOS_TABLE_DISCARDED_BITS) @@ -73,7 +73,7 @@ typedef union { #define VARIA_DATA_MASK (0x87FFFFFF & ~((1 << ACOS_TABLE_DISCARDED_BITS) - 1)) #define CONST_DATA_MASK (((1 << ACOS_TABLE_CONST_EXPONENT_BITS) - 1) \ - << (ACOS_TABLE_DATA_BITS - 1 + ACOS_TABLE_DISCARDED_BITS)) + << (ACOS_TABLE_DATA_BITS - 1 + ACOS_TABLE_DISCARDED_BITS)) #define SIGN_UNPACK_MASK (1 << (ACOS_TABLE_DATA_BITS - 1)) #define DATA_UNPACK_MASK ((1 << (ACOS_TABLE_DATA_BITS - 1)) - 1) @@ -105,107 +105,107 @@ dump_table_summary(void); extern int compute_table(void) { - uint32_t i; - float f; - FILE *acos_table_file; - size_t res; + uint32_t i; + float f; + FILE *acos_table_file; + size_t res; - acos_table_file = fopen(ACOS_TABLE_FILENAME, "w"); + acos_table_file = fopen(ACOS_TABLE_FILENAME, "w"); - for (i = 0; i < ACOS_TABLE_LENGTH; i++) { - f = acosf(float_from_index(i)); - res = fwrite(&f, sizeof(f), 1, acos_table_file); - if (res != 1) { - goto fail; - } - } + for (i = 0; i < ACOS_TABLE_LENGTH; i++) { + f = acosf(float_from_index(i)); + res = fwrite(&f, sizeof(f), 1, acos_table_file); + if (res != 1) { + goto fail; + } + } - res = fclose(acos_table_file); - if (res != 0) { - return -2; - } - return 0; + res = fclose(acos_table_file); + if (res != 0) { + return -2; + } + return 0; fail: - fclose(acos_table_file); - return -1; + fclose(acos_table_file); + return -1; } extern int init_fast_acosf(void) { - int ret, errsv; - FILE *acos_fp; - char err[150]; + int ret, errsv; + FILE *acos_fp; + char err[150]; - if (acos_table == NULL) { - ret = access(ACOS_TABLE_FILENAME, F_OK); - if (ret == -1) { - /* file doesn't exist, bad permissions, - * or some other error occured */ - errsv = errno; - strerror_r(errsv, err, 150); - if (errsv != ENOENT) return -1; - else { - switch_log_printf( - SWITCH_CHANNEL_LOG, - SWITCH_LOG_NOTICE, - "File [%s] doesn't exist. Creating file...\n", ACOS_TABLE_FILENAME - ); - ret = compute_table(); - if (ret != 0) return -2; - } - } else { - switch_log_printf( - SWITCH_CHANNEL_LOG, - SWITCH_LOG_INFO, - "Using previously created file [%s]\n", ACOS_TABLE_FILENAME - ); - } - } + if (acos_table == NULL) { + ret = access(ACOS_TABLE_FILENAME, F_OK); + if (ret == -1) { + /* file doesn't exist, bad permissions, + * or some other error occured */ + errsv = errno; + strerror_r(errsv, err, 150); + if (errsv != ENOENT) return -1; + else { + switch_log_printf( + SWITCH_CHANNEL_LOG, + SWITCH_LOG_NOTICE, + "File [%s] doesn't exist. Creating file...\n", ACOS_TABLE_FILENAME + ); + ret = compute_table(); + if (ret != 0) return -2; + } + } else { + switch_log_printf( + SWITCH_CHANNEL_LOG, + SWITCH_LOG_INFO, + "Using previously created file [%s]\n", ACOS_TABLE_FILENAME + ); + } + } - acos_fp = fopen(ACOS_TABLE_FILENAME, "r"); - if (acos_fp == NULL) return -3; - /* can't fail */ - acos_fd = fileno(acos_fp); - acos_table = (float *) mmap( - NULL, /* kernel chooses the address at which to create the mapping */ - ACOS_TABLE_LENGTH * sizeof(float), PROT_READ, MAP_SHARED, acos_fd, 0); - if (acos_table == MAP_FAILED) return -4; + acos_fp = fopen(ACOS_TABLE_FILENAME, "r"); + if (acos_fp == NULL) return -3; + /* can't fail */ + acos_fd = fileno(acos_fp); + acos_table = (float *) mmap( + NULL, /* kernel chooses the address at which to create the mapping */ + ACOS_TABLE_LENGTH * sizeof(float), PROT_READ, MAP_SHARED, acos_fd, 0); + if (acos_table == MAP_FAILED) return -4; - return 0; + return 0; } extern int destroy_fast_acosf(void) { - if (munmap(acos_table, ACOS_TABLE_LENGTH) == -1) return -1; - if (acos_fd != -1) { - if (close(acos_fd) == -1) return -2; - } - /* disable use of fast arc cosine file */ - acos_table = NULL; + if (munmap(acos_table, ACOS_TABLE_LENGTH) == -1) return -1; + if (acos_fd != -1) { + if (close(acos_fd) == -1) return -2; + } + /* disable use of fast arc cosine file */ + acos_table = NULL; - return 0; + return 0; } extern float fast_acosf(float x) { - return acos_table[index_from_float(x)]; + return acos_table[index_from_float(x)]; } static uint32_t index_from_float(float f) { - float_conv_t d; - d.f = f; - return ((d.i & SIGN_MASK) >> (32 - ACOS_TABLE_DATA_BITS)) | - ((d.i & DATA_MASK) >> ACOS_TABLE_DISCARDED_BITS); + float_conv_t d; + d.f = f; + return ((d.i & SIGN_MASK) >> (32 - ACOS_TABLE_DATA_BITS)) | + ((d.i & DATA_MASK) >> ACOS_TABLE_DISCARDED_BITS); } static float float_from_index(uint32_t d) { - float_conv_t f; - f.i = ((d & SIGN_UNPACK_MASK) << (32 - ACOS_TABLE_DATA_BITS)) | - ((d & DATA_UNPACK_MASK) << ACOS_TABLE_DISCARDED_BITS) | CONST_DATA_MASK; - return f.f; + float_conv_t f; + f.i = ((d & SIGN_UNPACK_MASK) << (32 - ACOS_TABLE_DATA_BITS)) | + ((d & DATA_UNPACK_MASK) << ACOS_TABLE_DISCARDED_BITS) | CONST_DATA_MASK; + return f.f; } #ifdef FAST_ACOSF_TESTING @@ -216,111 +216,111 @@ static float float_from_index(uint32_t d) static void debug_print(void) { - INF(ACOS_TABLE_CONST_EXPONENT); - INF(ACOS_TABLE_CONST_EXPONENT_BITS); - INF(ACOS_TABLE_FREE_EXPONENT_BITS); - INF(ACOS_TABLE_DISCARDED_BITS); - INF(ACOS_TABLE_DATA_BITS); - INF(ACOS_TABLE_LENGTH); - INFX(VARIA_DATA_MASK); - INFX(CONST_DATA_MASK); - INFX(SIGN_UNPACK_MASK); - INFX(DATA_UNPACK_MASK); - INFX(SIGN_MASK); - INFX(DATA_MASK); + INF(ACOS_TABLE_CONST_EXPONENT); + INF(ACOS_TABLE_CONST_EXPONENT_BITS); + INF(ACOS_TABLE_FREE_EXPONENT_BITS); + INF(ACOS_TABLE_DISCARDED_BITS); + INF(ACOS_TABLE_DATA_BITS); + INF(ACOS_TABLE_LENGTH); + INFX(VARIA_DATA_MASK); + INFX(CONST_DATA_MASK); + INFX(SIGN_UNPACK_MASK); + INFX(DATA_UNPACK_MASK); + INFX(SIGN_MASK); + INFX(DATA_MASK); } static void dump_table_summary(void) { - uint32_t i, i_0, i_1, di; - float f; + uint32_t i, i_0, i_1, di; + float f; - i = 1; - i_0 = index_from_float(0.0); - i_1 = index_from_float(1.0); - di = (i_1 - i_0)/100; - if (di == 0) di = 1; + i = 1; + i_0 = index_from_float(0.0); + i_1 = index_from_float(1.0); + di = (i_1 - i_0)/100; + if (di == 0) di = 1; - for (; i < ACOS_TABLE_LENGTH; i += di ) - { - f = float_from_index(i); - printf("-01i[%.10u] : ffi[%f] fa[%f] acos[%f]\n", - i, f, fast_acosf(f), acos(f)); - } + for (; i < ACOS_TABLE_LENGTH; i += di ) + { + f = float_from_index(i); + printf("-01i[%.10u] : ffi[%f] fa[%f] acos[%f]\n", + i, f, fast_acosf(f), acos(f)); + } - i = 1; - for (; i < ACOS_TABLE_LENGTH; i = (i << 1)) - { - f = fast_acosf(float_from_index(i)); - printf("--i[%.10u] : fa[%f] ffi[%f]\n", - i, f, float_from_index(i)); - } + i = 1; + for (; i < ACOS_TABLE_LENGTH; i = (i << 1)) + { + f = fast_acosf(float_from_index(i)); + printf("--i[%.10u] : fa[%f] ffi[%f]\n", + i, f, float_from_index(i)); + } - f = 0.0; - printf("i [%d] from float [%f]\n", index_from_float(f), f); - f = 0.1; - printf("i [%d] from float [%f]\n", index_from_float(f), f); - f = 0.2; - printf("i [%d] from float [%f]\n", index_from_float(f), f); - f = 0.3; - printf("i [%d] from float [%f]\n", index_from_float(f), f); - f = 0.4; - printf("i [%d] from float [%f]\n", index_from_float(f), f); - f = 0.5; - printf("i [%d] from float [%f]\n", index_from_float(f), f); - f = 0.6; - printf("i [%d] from float [%f]\n", index_from_float(f), f); - f = 0.7; - printf("i [%d] from float [%f]\n", index_from_float(f), f); - f = 7.5; - printf("i [%d] from float [%f]\n", index_from_float(f), f); - f = 0.8; - printf("i [%d] from float [%f]\n", index_from_float(f), f); - f = 0.9; - printf("i [%d] from float [%f]\n", index_from_float(f), f); - f = 0.95; - printf("i [%d] from float [%f]\n", index_from_float(f), f); - f = 0.99; - printf("i [%d] from float [%f]\n", index_from_float(f), f); - f = 1.0; - printf("i [%d] from float [%f]\n", index_from_float(f), f); - f = 1.1; - printf("i [%d] from float [%f]\n", index_from_float(f), f); - f = 1.2; - printf("i [%d] from float [%f]\n", index_from_float(f), f); - f = 0.0; - printf("i [%d] from float [%f]\n", index_from_float(f), f); - f = -0.1; - printf("i [%d] from float [%f]\n", index_from_float(f), f); - f = -0.2; - printf("i [%d] from float [%f]\n", index_from_float(f), f); - f = -0.3; - printf("i [%d] from float [%f]\n", index_from_float(f), f); - f = -0.4; - printf("i [%d] from float [%f]\n", index_from_float(f), f); - f = -0.5; - printf("i [%d] from float [%f]\n", index_from_float(f), f); - f = -0.6; - printf("i [%d] from float [%f]\n", index_from_float(f), f); - f = -0.7; - printf("i [%d] from float [%f]\n", index_from_float(f), f); - f = -7.5; - printf("i [%d] from float [%f]\n", index_from_float(f), f); - f = -0.8; - printf("i [%d] from float [%f]\n", index_from_float(f), f); - f = -0.9; - printf("i [%d] from float [%f]\n", index_from_float(f), f); - f = -0.95; - printf("i [%d] from float [%f]\n", index_from_float(f), f); - f = -0.99; - printf("i [%d] from float [%f]\n", index_from_float(f), f); - f = -1.0; - printf("i [%d] from float [%f]\n", index_from_float(f), f); - f = -1.1; - printf("i [%d] from float [%f]\n", index_from_float(f), f); - f = -1.2; - printf("i [%d] from float [%f]\n", index_from_float(f), f); + f = 0.0; + printf("i [%d] from float [%f]\n", index_from_float(f), f); + f = 0.1; + printf("i [%d] from float [%f]\n", index_from_float(f), f); + f = 0.2; + printf("i [%d] from float [%f]\n", index_from_float(f), f); + f = 0.3; + printf("i [%d] from float [%f]\n", index_from_float(f), f); + f = 0.4; + printf("i [%d] from float [%f]\n", index_from_float(f), f); + f = 0.5; + printf("i [%d] from float [%f]\n", index_from_float(f), f); + f = 0.6; + printf("i [%d] from float [%f]\n", index_from_float(f), f); + f = 0.7; + printf("i [%d] from float [%f]\n", index_from_float(f), f); + f = 7.5; + printf("i [%d] from float [%f]\n", index_from_float(f), f); + f = 0.8; + printf("i [%d] from float [%f]\n", index_from_float(f), f); + f = 0.9; + printf("i [%d] from float [%f]\n", index_from_float(f), f); + f = 0.95; + printf("i [%d] from float [%f]\n", index_from_float(f), f); + f = 0.99; + printf("i [%d] from float [%f]\n", index_from_float(f), f); + f = 1.0; + printf("i [%d] from float [%f]\n", index_from_float(f), f); + f = 1.1; + printf("i [%d] from float [%f]\n", index_from_float(f), f); + f = 1.2; + printf("i [%d] from float [%f]\n", index_from_float(f), f); + f = 0.0; + printf("i [%d] from float [%f]\n", index_from_float(f), f); + f = -0.1; + printf("i [%d] from float [%f]\n", index_from_float(f), f); + f = -0.2; + printf("i [%d] from float [%f]\n", index_from_float(f), f); + f = -0.3; + printf("i [%d] from float [%f]\n", index_from_float(f), f); + f = -0.4; + printf("i [%d] from float [%f]\n", index_from_float(f), f); + f = -0.5; + printf("i [%d] from float [%f]\n", index_from_float(f), f); + f = -0.6; + printf("i [%d] from float [%f]\n", index_from_float(f), f); + f = -0.7; + printf("i [%d] from float [%f]\n", index_from_float(f), f); + f = -7.5; + printf("i [%d] from float [%f]\n", index_from_float(f), f); + f = -0.8; + printf("i [%d] from float [%f]\n", index_from_float(f), f); + f = -0.9; + printf("i [%d] from float [%f]\n", index_from_float(f), f); + f = -0.95; + printf("i [%d] from float [%f]\n", index_from_float(f), f); + f = -0.99; + printf("i [%d] from float [%f]\n", index_from_float(f), f); + f = -1.0; + printf("i [%d] from float [%f]\n", index_from_float(f), f); + f = -1.1; + printf("i [%d] from float [%f]\n", index_from_float(f), f); + f = -1.2; + printf("i [%d] from float [%f]\n", index_from_float(f), f); } #endif /* FAST_ACOSF_TESTING */ diff --git a/src/mod/applications/mod_avmd/avmd_fast_acosf.h b/src/mod/applications/mod_avmd/avmd_fast_acosf.h index 8de7954def..93e43ba438 100644 --- a/src/mod/applications/mod_avmd/avmd_fast_acosf.h +++ b/src/mod/applications/mod_avmd/avmd_fast_acosf.h @@ -5,7 +5,7 @@ * Contributor(s): * * Eric des Courtis - * Piotr Gregor + * Piotr Gregor */ diff --git a/src/mod/applications/mod_avmd/avmd_fir.h b/src/mod/applications/mod_avmd/avmd_fir.h index 25a2c23bb3..12dd1019ae 100644 --- a/src/mod/applications/mod_avmd/avmd_fir.h +++ b/src/mod/applications/mod_avmd/avmd_fir.h @@ -3,9 +3,9 @@ * * Contributor(s): * - * Piotr Gregor + * Piotr Gregor * - * @date 23 Mar 2016 + * @date 23 Mar 2016 */ @@ -15,7 +15,7 @@ #define AVMD_MAX(a, b) (a) > (b) ? (a) : (b) #define AVMD_MEDIAN_FILTER(a, b, c) (a) > (b) ? ((a) > (c) ? \ - AVMD_MAX((b), (c)) : a) : ((b) > (c) ? AVMD_MAX((a), (c)) : (b)) + AVMD_MAX((b), (c)) : a) : ((b) > (c) ? AVMD_MAX((a), (c)) : (b)) #endif diff --git a/src/mod/applications/mod_avmd/avmd_goertzel.c b/src/mod/applications/mod_avmd/avmd_goertzel.c index 5f05c00b22..15650397bc 100644 --- a/src/mod/applications/mod_avmd/avmd_goertzel.c +++ b/src/mod/applications/mod_avmd/avmd_goertzel.c @@ -8,30 +8,30 @@ #include #ifndef __AVMD_GOERTZEL_H__ - #include "avmd_goertzel.h" + #include "avmd_goertzel.h" #endif #ifndef __AVMD_BUFFER_H__ - #include "avmd_buffer.h" + #include "avmd_buffer.h" #endif extern double avmd_goertzel(circ_buffer_t *b, size_t pos, double f, size_t num) { - double s = 0.0; - double p = 0.0; - double p2 = 0.0; - double coeff; - size_t i; + double s = 0.0; + double p = 0.0; + double p2 = 0.0; + double coeff; + size_t i; - coeff = 2.0 * cos(2.0 * M_PI * f); + coeff = 2.0 * cos(2.0 * M_PI * f); - for (i = 0; i < num; i++) { - /* TODO: optimize to avoid GET_SAMPLE when possible */ - s = GET_SAMPLE(b, i + pos) + (coeff * p) - p2; - p2 = p; - p = s; - } + for (i = 0; i < num; i++) { + /* TODO: optimize to avoid GET_SAMPLE when possible */ + s = GET_SAMPLE(b, i + pos) + (coeff * p) - p2; + p2 = p; + p = s; + } - return (p2 * p2) + (p * p) - (coeff * p2 * p); + return (p2 * p2) + (p * p) - (coeff * p2 * p); } diff --git a/src/mod/applications/mod_avmd/avmd_goertzel.h b/src/mod/applications/mod_avmd/avmd_goertzel.h index 21ba3f5154..be7920c933 100644 --- a/src/mod/applications/mod_avmd/avmd_goertzel.h +++ b/src/mod/applications/mod_avmd/avmd_goertzel.h @@ -12,14 +12,14 @@ #ifndef _MSC_VER - #include + #include #endif #include "avmd_buffer.h" #if !defined(M_PI) - /* C99 systems may not define M_PI */ - #define M_PI 3.14159265358979323846264338327 + /* C99 systems may not define M_PI */ + #define M_PI 3.14159265358979323846264338327 #endif diff --git a/src/mod/applications/mod_avmd/avmd_options.h b/src/mod/applications/mod_avmd/avmd_options.h index a580af811e..f1c23dcc55 100644 --- a/src/mod/applications/mod_avmd/avmd_options.h +++ b/src/mod/applications/mod_avmd/avmd_options.h @@ -5,7 +5,7 @@ * * Contributor(s): * - * Piotr Gregor + * Piotr Gregor */ diff --git a/src/mod/applications/mod_avmd/avmd_psi.h b/src/mod/applications/mod_avmd/avmd_psi.h index dbbf401282..49f22090a9 100644 --- a/src/mod/applications/mod_avmd/avmd_psi.h +++ b/src/mod/applications/mod_avmd/avmd_psi.h @@ -2,7 +2,7 @@ * Contributor(s): * * Eric des Courtis - * Piotr Gregor + * Piotr Gregor */ diff --git a/src/mod/applications/mod_avmd/avmd_sma_buf.h b/src/mod/applications/mod_avmd/avmd_sma_buf.h index e3051c9731..0ee1aa5a9e 100644 --- a/src/mod/applications/mod_avmd/avmd_sma_buf.h +++ b/src/mod/applications/mod_avmd/avmd_sma_buf.h @@ -4,7 +4,7 @@ * Contributor(s): * * Eric des Courtis - * Piotr Gregor + * Piotr Gregor */ @@ -22,22 +22,22 @@ #include "avmd_buffer.h" typedef struct { - size_t len; - BUFF_TYPE *data; - BUFF_TYPE sma; - size_t pos; - size_t lpos; + size_t len; + BUFF_TYPE *data; + BUFF_TYPE sma; + size_t pos; + size_t lpos; } sma_buffer_t; #define INIT_SMA_BUFFER(b, l, s) \ - { \ + { \ (void)memset((b), 0, sizeof(sma_buffer_t)); \ (b)->len = (l); \ (b)->data = (BUFF_TYPE *)switch_core_session_alloc((s), sizeof(BUFF_TYPE) * (l)); \ (b)->sma = 0.0; \ (b)->pos = 0; \ (b)->lpos = 0; \ - } + } #define GET_SMA_SAMPLE(b, p) ((b)->data[(p) % (b)->len]) #define SET_SMA_SAMPLE(b, p, v) ((b)->data[(p) % (b)->len] = (v)) @@ -45,33 +45,33 @@ typedef struct { #define GET_CURRENT_SMA_LPOS(b) ((b)->lpos) #define INC_SMA_POS(b) \ - { \ + { \ ((b)->lpos + 1 < 2 * (b)->len) ? ((b)->lpos++) : ((b)->lpos = (b)->len); \ (b)->pos = (b)->lpos % (b)->len; \ - } + } #define APPEND_SMA_VAL(b, v) \ - { \ + { \ (b)->sma -= ((b)->data[(b)->pos] / (BUFF_TYPE)(b)->len); \ (b)->data[(b)->pos] = (v); \ (((b)->lpos) >= ((b)->len)) ? ((b)->sma += ((b)->data[(b)->pos] / (BUFF_TYPE)(b)->len)) : \ - ((b)->sma = ((((b)->sma)*((b)->pos)) + ((b)->data[(b)->pos])) / ((BUFF_TYPE)(((b)->pos) + 1))) ; \ + ((b)->sma = ((((b)->sma)*((b)->pos)) + ((b)->data[(b)->pos])) / ((BUFF_TYPE)(((b)->pos) + 1))) ; \ INC_SMA_POS(b); \ - } + } #define RESET_SMA_BUFFER(b) \ - { \ + { \ (b)->sma = 0.0; \ (void)memset((b)->data, 0, sizeof(BUFF_TYPE) * (b)->len); \ (b)->pos = 0; \ (b)->lpos = 0; \ - } + } /* #define DESTROY_SMA_BUFFER(b) \ - do{ \ + do{ \ free((b)->data); \ - }while(0); + }while(0); */ @@ -83,19 +83,19 @@ typedef struct { int main(void) { - int i; - sma_buffer_t b; + int i; + sma_buffer_t b; - INIT_SMA_BUFFER(&b, 100); + INIT_SMA_BUFFER(&b, 100); - for(i = 0; i < 20; i++){ + for(i = 0; i < 20; i++){ APPEND_SMA_VAL(&b, 100.0); printf("SMA = %lf\n", b.sma); - } + } - DESTROY_SMA_BUFFER(&b); + DESTROY_SMA_BUFFER(&b); - return EXIT_SUCCESS; + return EXIT_SUCCESS; } */ diff --git a/src/mod/applications/mod_avmd/conf/autoload_configs/avmd.conf.xml b/src/mod/applications/mod_avmd/conf/autoload_configs/avmd.conf.xml index 86b2500bad..cfd710f530 100644 --- a/src/mod/applications/mod_avmd/conf/autoload_configs/avmd.conf.xml +++ b/src/mod/applications/mod_avmd/conf/autoload_configs/avmd.conf.xml @@ -1,74 +1,74 @@ - + - + - + - - + + - - + + - - - + + + - + - - + + - - + + - - + + - - + + - - + + - - + + - - + + - - + + - - + + - - + + - - + + diff --git a/src/mod/applications/mod_avmd/conf/avmd_test_dialplan.xml b/src/mod/applications/mod_avmd/conf/avmd_test_dialplan.xml index de567a8350..2a85ec7a60 100644 --- a/src/mod/applications/mod_avmd/conf/avmd_test_dialplan.xml +++ b/src/mod/applications/mod_avmd/conf/avmd_test_dialplan.xml @@ -1,840 +1,840 @@ - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + - - - - - - - - + + + + + + + + diff --git a/src/mod/applications/mod_avmd/mod_avmd.c b/src/mod/applications/mod_avmd/mod_avmd.c index ea1c5f483a..dde3dfbf93 100644 --- a/src/mod/applications/mod_avmd/mod_avmd.c +++ b/src/mod/applications/mod_avmd/mod_avmd.c @@ -20,7 +20,7 @@ * Contributor(s): * * Eric des Courtis - * Piotr Gregor + * Piotr Gregor * * mod_avmd.c -- Advanced Voicemail Detection Module * @@ -39,14 +39,14 @@ #include #ifdef WIN32 - #include - #define ISNAN(x) (!!(_isnan(x))) - #define ISINF(x) (isinf(x)) + #include + #define ISNAN(x) (!!(_isnan(x))) + #define ISINF(x) (isinf(x)) #else - int __isnan(double); + int __isnan(double); int __isinf(double); - #define ISNAN(x) (__isnan(x)) - #define ISINF(x) (__isinf(x)) + #define ISNAN(x) (__isnan(x)) + #define ISINF(x) (__isinf(x)) #endif #include "avmd_buffer.h" @@ -119,16 +119,16 @@ /* don't forget to update avmd_events_str table if you modify this */ enum avmd_event { - AVMD_EVENT_BEEP = 0, - AVMD_EVENT_SESSION_START = 1, - AVMD_EVENT_SESSION_STOP = 2 + AVMD_EVENT_BEEP = 0, + AVMD_EVENT_SESSION_START = 1, + AVMD_EVENT_SESSION_STOP = 2 }; /* This array MUST be NULL terminated! */ const char* avmd_events_str[] = { - [AVMD_EVENT_BEEP] = "avmd::beep", - [AVMD_EVENT_SESSION_START] = "avmd::start", - [AVMD_EVENT_SESSION_STOP] = "avmd::stop", - NULL /* MUST be last and always here */ + [AVMD_EVENT_BEEP] = "avmd::beep", + [AVMD_EVENT_SESSION_START] = "avmd::start", + [AVMD_EVENT_SESSION_STOP] = "avmd::stop", + NULL /* MUST be last and always here */ }; #define AVMD_CHAR_BUF_LEN 20u @@ -136,17 +136,17 @@ const char* avmd_events_str[] = { enum avmd_app { - AVMD_APP_START_APP = 0, - AVMD_APP_STOP_APP = 1, - AVMD_APP_START_FUNCTION = 2 /* deprecated since version 1.6.8 */ + AVMD_APP_START_APP = 0, + AVMD_APP_STOP_APP = 1, + AVMD_APP_START_FUNCTION = 2 /* deprecated since version 1.6.8 */ }; enum avmd_detection_mode { - AVMD_DETECT_AMP = 0, - AVMD_DETECT_FREQ = 1, - AVMD_DETECT_BOTH = 2, - AVMD_DETECT_NONE = 3 + AVMD_DETECT_AMP = 0, + AVMD_DETECT_FREQ = 1, + AVMD_DETECT_BOTH = 2, + AVMD_DETECT_NONE = 3 }; /* Prototypes */ @@ -159,92 +159,92 @@ SWITCH_STANDARD_APP(avmd_stop_app); SWITCH_STANDARD_APP(avmd_start_function); struct avmd_settings { - uint8_t debug; - uint8_t report_status; - uint8_t fast_math; - uint8_t require_continuous_streak; - uint16_t sample_n_continuous_streak; - uint16_t sample_n_to_skip; - uint8_t require_continuous_streak_amp; - uint16_t sample_n_continuous_streak_amp; - uint8_t simplified_estimation; - uint8_t inbound_channnel; - uint8_t outbound_channnel; - enum avmd_detection_mode mode; - uint8_t detectors_n; - uint8_t detectors_lagged_n; + uint8_t debug; + uint8_t report_status; + uint8_t fast_math; + uint8_t require_continuous_streak; + uint16_t sample_n_continuous_streak; + uint16_t sample_n_to_skip; + uint8_t require_continuous_streak_amp; + uint16_t sample_n_continuous_streak_amp; + uint8_t simplified_estimation; + uint8_t inbound_channnel; + uint8_t outbound_channnel; + enum avmd_detection_mode mode; + uint8_t detectors_n; + uint8_t detectors_lagged_n; }; /*! Status of the beep detection */ typedef enum { - BEEP_DETECTED, - BEEP_NOTDETECTED + BEEP_DETECTED, + BEEP_NOTDETECTED } avmd_beep_state_t; /*! Data related to the current status of the beep */ typedef struct { - avmd_beep_state_t beep_state; - size_t last_beep; + avmd_beep_state_t beep_state; + size_t last_beep; } avmd_state_t; struct avmd_session; typedef struct avmd_session avmd_session_t; struct avmd_buffer { - sma_buffer_t sma_b; - sma_buffer_t sqa_b; + sma_buffer_t sma_b; + sma_buffer_t sqa_b; - sma_buffer_t sma_b_fir; - sma_buffer_t sqa_b_fir; + sma_buffer_t sma_b_fir; + sma_buffer_t sqa_b_fir; - sma_buffer_t sma_amp_b; - sma_buffer_t sqa_amp_b; + sma_buffer_t sma_amp_b; + sma_buffer_t sqa_amp_b; - uint8_t resolution; - uint8_t offset; - double amplitude_max; - size_t samples_streak, samples_streak_amp; /* number of DESA samples in single streak without reset needed to validate SMA estimator */ + uint8_t resolution; + uint8_t offset; + double amplitude_max; + size_t samples_streak, samples_streak_amp; /* number of DESA samples in single streak without reset needed to validate SMA estimator */ }; struct avmd_detector { - switch_thread_t *thread; - switch_mutex_t *mutex; - uint8_t flag_processing_done; - uint8_t flag_should_exit; - enum avmd_detection_mode result; - switch_thread_cond_t *cond_start_processing; - struct avmd_buffer buffer; - avmd_session_t *s; - size_t samples; - uint8_t idx; - uint8_t lagged, lag; + switch_thread_t *thread; + switch_mutex_t *mutex; + uint8_t flag_processing_done; + uint8_t flag_should_exit; + enum avmd_detection_mode result; + switch_thread_cond_t *cond_start_processing; + struct avmd_buffer buffer; + avmd_session_t *s; + size_t samples; + uint8_t idx; + uint8_t lagged, lag; }; /*! Type that holds avmd detection session information. */ struct avmd_session { - switch_core_session_t *session; - switch_mutex_t *mutex; - struct avmd_settings settings; - uint32_t rate; - circ_buffer_t b; - size_t pos; - double f; - avmd_state_t state; - switch_time_t start_time, stop_time, detection_start_time, detection_stop_time; - size_t frame_n; - uint8_t frame_n_to_skip; + switch_core_session_t *session; + switch_mutex_t *mutex; + struct avmd_settings settings; + uint32_t rate; + circ_buffer_t b; + size_t pos; + double f; + avmd_state_t state; + switch_time_t start_time, stop_time, detection_start_time, detection_stop_time; + size_t frame_n; + uint8_t frame_n_to_skip; - switch_mutex_t *mutex_detectors_done; - switch_thread_cond_t *cond_detectors_done; - struct avmd_detector *detectors; + switch_mutex_t *mutex_detectors_done; + switch_thread_cond_t *cond_detectors_done; + struct avmd_detector *detectors; }; static struct avmd_globals { - switch_mutex_t *mutex; - struct avmd_settings settings; - switch_memory_pool_t *pool; - size_t session_n; + switch_mutex_t *mutex; + struct avmd_settings settings; + switch_memory_pool_t *pool; + size_t session_n; } avmd_globals; static void avmd_process(avmd_session_t *session, switch_frame_t *frame, uint8_t direction); @@ -255,7 +255,7 @@ static switch_status_t avmd_register_all_events(void); static void avmd_unregister_all_events(void); static void avmd_fire_event(enum avmd_event type, switch_core_session_t *fs_s, double freq, double v_freq, double amp, double v_amp, avmd_beep_state_t beep_status, uint8_t info, - switch_time_t detection_start_time, switch_time_t detection_stop_time, switch_time_t start_time, switch_time_t stop_time, uint8_t resolution, uint8_t offset, uint8_t idx); + switch_time_t detection_start_time, switch_time_t detection_stop_time, switch_time_t start_time, switch_time_t stop_time, uint8_t resolution, uint8_t offset, uint8_t idx); static enum avmd_detection_mode avmd_process_sample(avmd_session_t *s, circ_buffer_t *b, size_t sample_n, size_t pos, struct avmd_detector *d); @@ -286,9 +286,9 @@ static uint8_t avmd_detection_in_progress(avmd_session_t *s); static switch_status_t avmd_launch_threads(avmd_session_t *s) { - uint8_t idx; - struct avmd_detector *d; - switch_threadattr_t *thd_attr = NULL; + uint8_t idx; + struct avmd_detector *d; + switch_threadattr_t *thd_attr = NULL; idx = 0; while (idx < s->settings.detectors_n) { @@ -336,226 +336,226 @@ static switch_status_t avmd_launch_threads(avmd_session_t *s) { } static void avmd_join_threads(avmd_session_t *s) { - uint8_t idx; - struct avmd_detector *d; - switch_status_t status; + uint8_t idx; + struct avmd_detector *d; + switch_status_t status; - idx = 0; - while (idx < s->settings.detectors_n) { - d = &s->detectors[idx]; - switch_mutex_lock(d->mutex); - if (d->thread != NULL) { - d->flag_should_exit = 1; - d->samples = 0; - switch_thread_cond_signal(d->cond_start_processing); - switch_mutex_unlock(d->mutex); - switch_thread_join(&status, d->thread); - d->thread = NULL; - switch_mutex_destroy(d->mutex); - switch_thread_cond_destroy(d->cond_start_processing); - } else { - switch_mutex_unlock(d->mutex); - } - ++idx; - } - idx = 0; - while (idx < s->settings.detectors_lagged_n) { - d = &s->detectors[s->settings.detectors_n + idx]; - switch_mutex_lock(d->mutex); - if (d->thread != NULL) { - d->flag_should_exit = 1; - d->samples = 0; - switch_thread_cond_signal(d->cond_start_processing); - switch_mutex_unlock(d->mutex); - switch_thread_join(&status, d->thread); - d->thread = NULL; - switch_mutex_destroy(d->mutex); - switch_thread_cond_destroy(d->cond_start_processing); - } else { - switch_mutex_unlock(d->mutex); - } - ++idx; - } + idx = 0; + while (idx < s->settings.detectors_n) { + d = &s->detectors[idx]; + switch_mutex_lock(d->mutex); + if (d->thread != NULL) { + d->flag_should_exit = 1; + d->samples = 0; + switch_thread_cond_signal(d->cond_start_processing); + switch_mutex_unlock(d->mutex); + switch_thread_join(&status, d->thread); + d->thread = NULL; + switch_mutex_destroy(d->mutex); + switch_thread_cond_destroy(d->cond_start_processing); + } else { + switch_mutex_unlock(d->mutex); + } + ++idx; + } + idx = 0; + while (idx < s->settings.detectors_lagged_n) { + d = &s->detectors[s->settings.detectors_n + idx]; + switch_mutex_lock(d->mutex); + if (d->thread != NULL) { + d->flag_should_exit = 1; + d->samples = 0; + switch_thread_cond_signal(d->cond_start_processing); + switch_mutex_unlock(d->mutex); + switch_thread_join(&status, d->thread); + d->thread = NULL; + switch_mutex_destroy(d->mutex); + switch_thread_cond_destroy(d->cond_start_processing); + } else { + switch_mutex_unlock(d->mutex); + } + ++idx; + } } static switch_status_t avmd_init_buffer(struct avmd_buffer *b, size_t buf_sz, uint8_t resolution, uint8_t offset, switch_core_session_t *fs_session) { - INIT_SMA_BUFFER(&b->sma_b, buf_sz, fs_session); - if (b->sma_b.data == NULL) { - return SWITCH_STATUS_FALSE; - } - memset(b->sma_b.data, 0, sizeof(BUFF_TYPE) * buf_sz); + INIT_SMA_BUFFER(&b->sma_b, buf_sz, fs_session); + if (b->sma_b.data == NULL) { + return SWITCH_STATUS_FALSE; + } + memset(b->sma_b.data, 0, sizeof(BUFF_TYPE) * buf_sz); - INIT_SMA_BUFFER(&b->sqa_b, buf_sz, fs_session); - if (b->sqa_b.data == NULL) { - return SWITCH_STATUS_FALSE; - } - memset(b->sqa_b.data, 0, sizeof(BUFF_TYPE) * buf_sz); + INIT_SMA_BUFFER(&b->sqa_b, buf_sz, fs_session); + if (b->sqa_b.data == NULL) { + return SWITCH_STATUS_FALSE; + } + memset(b->sqa_b.data, 0, sizeof(BUFF_TYPE) * buf_sz); - INIT_SMA_BUFFER(&b->sma_b_fir, buf_sz, fs_session); - if (b->sma_b_fir.data == NULL) { - return SWITCH_STATUS_FALSE; - } - memset(b->sma_b_fir.data, 0, sizeof(BUFF_TYPE) * buf_sz); + INIT_SMA_BUFFER(&b->sma_b_fir, buf_sz, fs_session); + if (b->sma_b_fir.data == NULL) { + return SWITCH_STATUS_FALSE; + } + memset(b->sma_b_fir.data, 0, sizeof(BUFF_TYPE) * buf_sz); - INIT_SMA_BUFFER(&b->sqa_b_fir, buf_sz, fs_session); - if (b->sqa_b_fir.data == NULL) { - return SWITCH_STATUS_FALSE; - } - memset(b->sqa_b_fir.data, 0, sizeof(BUFF_TYPE) * buf_sz); + INIT_SMA_BUFFER(&b->sqa_b_fir, buf_sz, fs_session); + if (b->sqa_b_fir.data == NULL) { + return SWITCH_STATUS_FALSE; + } + memset(b->sqa_b_fir.data, 0, sizeof(BUFF_TYPE) * buf_sz); - INIT_SMA_BUFFER(&b->sma_amp_b, buf_sz, fs_session); - if (b->sma_amp_b.data == NULL) { - return SWITCH_STATUS_FALSE; - } - memset(b->sma_amp_b.data, 0, sizeof(BUFF_TYPE) * buf_sz); + INIT_SMA_BUFFER(&b->sma_amp_b, buf_sz, fs_session); + if (b->sma_amp_b.data == NULL) { + return SWITCH_STATUS_FALSE; + } + memset(b->sma_amp_b.data, 0, sizeof(BUFF_TYPE) * buf_sz); - INIT_SMA_BUFFER(&b->sqa_amp_b, buf_sz, fs_session); - if (b->sqa_amp_b.data == NULL) { - return SWITCH_STATUS_FALSE; - } - memset(b->sqa_amp_b.data, 0, sizeof(BUFF_TYPE) * buf_sz); + INIT_SMA_BUFFER(&b->sqa_amp_b, buf_sz, fs_session); + if (b->sqa_amp_b.data == NULL) { + return SWITCH_STATUS_FALSE; + } + memset(b->sqa_amp_b.data, 0, sizeof(BUFF_TYPE) * buf_sz); - b->amplitude_max = 0.0; - b->samples_streak = 0; - b->samples_streak_amp = 0; - b->resolution = resolution; - b->offset = offset; + b->amplitude_max = 0.0; + b->samples_streak = 0; + b->samples_streak_amp = 0; + b->resolution = resolution; + b->offset = offset; - return SWITCH_STATUS_SUCCESS; + return SWITCH_STATUS_SUCCESS; } -/*! \brief The avmd session data initialization function. - * @param avmd_session A reference to a avmd session. - * @param fs_session A reference to a FreeSWITCH session. +/*! \brief The avmd session data initialization function. + * @param avmd_session A reference to a avmd session. + * @param fs_session A reference to a FreeSWITCH session. * @details Avmd globals mutex must be locked. */ static switch_status_t init_avmd_session_data(avmd_session_t *avmd_session, switch_core_session_t *fs_session, switch_mutex_t *mutex) { - uint8_t idx, resolution, offset; - size_t buf_sz; - struct avmd_detector *d; - switch_status_t status = SWITCH_STATUS_SUCCESS; + uint8_t idx, resolution, offset; + size_t buf_sz; + struct avmd_detector *d; + switch_status_t status = SWITCH_STATUS_SUCCESS; - if (mutex != NULL) - { - switch_mutex_lock(mutex); - } + if (mutex != NULL) + { + switch_mutex_lock(mutex); + } - /*! This is a worst case sample rate estimate */ - avmd_session->rate = 48000; - INIT_CIRC_BUFFER(&avmd_session->b, (size_t) AVMD_BEEP_LEN(avmd_session->rate), (size_t) AVMD_FRAME_LEN(avmd_session->rate), fs_session); - if (avmd_session->b.buf == NULL) { - status = SWITCH_STATUS_MEMERR; - goto end; - } - avmd_session->session = fs_session; - avmd_session->pos = 0; - avmd_session->f = 0.0; - avmd_session->state.last_beep = 0; - avmd_session->state.beep_state = BEEP_NOTDETECTED; - switch_mutex_init(&avmd_session->mutex, SWITCH_MUTEX_DEFAULT, switch_core_session_get_pool(fs_session)); - avmd_session->frame_n = 0; - avmd_session->detection_start_time = 0; - avmd_session->detection_stop_time = 0; - avmd_session->frame_n_to_skip = 0; + /*! This is a worst case sample rate estimate */ + avmd_session->rate = 48000; + INIT_CIRC_BUFFER(&avmd_session->b, (size_t) AVMD_BEEP_LEN(avmd_session->rate), (size_t) AVMD_FRAME_LEN(avmd_session->rate), fs_session); + if (avmd_session->b.buf == NULL) { + status = SWITCH_STATUS_MEMERR; + goto end; + } + avmd_session->session = fs_session; + avmd_session->pos = 0; + avmd_session->f = 0.0; + avmd_session->state.last_beep = 0; + avmd_session->state.beep_state = BEEP_NOTDETECTED; + switch_mutex_init(&avmd_session->mutex, SWITCH_MUTEX_DEFAULT, switch_core_session_get_pool(fs_session)); + avmd_session->frame_n = 0; + avmd_session->detection_start_time = 0; + avmd_session->detection_stop_time = 0; + avmd_session->frame_n_to_skip = 0; - buf_sz = AVMD_BEEP_LEN((uint32_t)avmd_session->rate) / (uint32_t) AVMD_SINE_LEN(avmd_session->rate); - if (buf_sz < 1) { - status = SWITCH_STATUS_MORE_DATA; - goto end; - } - avmd_session->detectors = (struct avmd_detector*) switch_core_session_alloc(fs_session, (avmd_session->settings.detectors_n + avmd_session->settings.detectors_lagged_n) * sizeof(struct avmd_detector)); - if (avmd_session->detectors == NULL) { - switch_log_printf(SWITCH_CHANNEL_SESSION_LOG(fs_session), SWITCH_LOG_ERROR, "Can't allocate memory for avmd detectors!\n"); - status = SWITCH_STATUS_NOT_INITALIZED; - goto end; - } - idx = 0; - resolution = 0; - while (idx < avmd_session->settings.detectors_n) { - ++resolution; - offset = 0; - while ((offset < resolution) && (idx < avmd_session->settings.detectors_n)) { - d = &avmd_session->detectors[idx]; - if (avmd_init_buffer(&d->buffer, buf_sz, resolution, offset, fs_session) != SWITCH_STATUS_SUCCESS) { - status = SWITCH_STATUS_FALSE; - goto end; - } - d->s = avmd_session; - d->flag_processing_done = 1; - d->flag_should_exit = 1; - d->idx = idx; - d->thread = NULL; - switch_mutex_init(&d->mutex, SWITCH_MUTEX_DEFAULT, switch_core_session_get_pool(fs_session)); - switch_thread_cond_create(&d->cond_start_processing, switch_core_session_get_pool(fs_session)); - ++offset; - ++idx; - } - } - idx = 0; - resolution = 1; - offset = 0; - while (idx < avmd_session->settings.detectors_lagged_n) { - d = &avmd_session->detectors[avmd_session->settings.detectors_n + idx]; - if (avmd_init_buffer(&d->buffer, buf_sz, resolution, offset, fs_session) != SWITCH_STATUS_SUCCESS) { - status = SWITCH_STATUS_FALSE; - goto end; - } - d->s = avmd_session; - d->flag_processing_done = 1; - d->flag_should_exit = 1; - d->idx = avmd_session->settings.detectors_n + idx; - d->thread = NULL; - switch_mutex_init(&d->mutex, SWITCH_MUTEX_DEFAULT, switch_core_session_get_pool(fs_session)); - switch_thread_cond_create(&d->cond_start_processing, switch_core_session_get_pool(fs_session)); - ++idx; - } - switch_mutex_init(&avmd_session->mutex_detectors_done, SWITCH_MUTEX_DEFAULT, switch_core_session_get_pool(fs_session)); - switch_thread_cond_create(&avmd_session->cond_detectors_done, switch_core_session_get_pool(fs_session)); + buf_sz = AVMD_BEEP_LEN((uint32_t)avmd_session->rate) / (uint32_t) AVMD_SINE_LEN(avmd_session->rate); + if (buf_sz < 1) { + status = SWITCH_STATUS_MORE_DATA; + goto end; + } + avmd_session->detectors = (struct avmd_detector*) switch_core_session_alloc(fs_session, (avmd_session->settings.detectors_n + avmd_session->settings.detectors_lagged_n) * sizeof(struct avmd_detector)); + if (avmd_session->detectors == NULL) { + switch_log_printf(SWITCH_CHANNEL_SESSION_LOG(fs_session), SWITCH_LOG_ERROR, "Can't allocate memory for avmd detectors!\n"); + status = SWITCH_STATUS_NOT_INITALIZED; + goto end; + } + idx = 0; + resolution = 0; + while (idx < avmd_session->settings.detectors_n) { + ++resolution; + offset = 0; + while ((offset < resolution) && (idx < avmd_session->settings.detectors_n)) { + d = &avmd_session->detectors[idx]; + if (avmd_init_buffer(&d->buffer, buf_sz, resolution, offset, fs_session) != SWITCH_STATUS_SUCCESS) { + status = SWITCH_STATUS_FALSE; + goto end; + } + d->s = avmd_session; + d->flag_processing_done = 1; + d->flag_should_exit = 1; + d->idx = idx; + d->thread = NULL; + switch_mutex_init(&d->mutex, SWITCH_MUTEX_DEFAULT, switch_core_session_get_pool(fs_session)); + switch_thread_cond_create(&d->cond_start_processing, switch_core_session_get_pool(fs_session)); + ++offset; + ++idx; + } + } + idx = 0; + resolution = 1; + offset = 0; + while (idx < avmd_session->settings.detectors_lagged_n) { + d = &avmd_session->detectors[avmd_session->settings.detectors_n + idx]; + if (avmd_init_buffer(&d->buffer, buf_sz, resolution, offset, fs_session) != SWITCH_STATUS_SUCCESS) { + status = SWITCH_STATUS_FALSE; + goto end; + } + d->s = avmd_session; + d->flag_processing_done = 1; + d->flag_should_exit = 1; + d->idx = avmd_session->settings.detectors_n + idx; + d->thread = NULL; + switch_mutex_init(&d->mutex, SWITCH_MUTEX_DEFAULT, switch_core_session_get_pool(fs_session)); + switch_thread_cond_create(&d->cond_start_processing, switch_core_session_get_pool(fs_session)); + ++idx; + } + switch_mutex_init(&avmd_session->mutex_detectors_done, SWITCH_MUTEX_DEFAULT, switch_core_session_get_pool(fs_session)); + switch_thread_cond_create(&avmd_session->cond_detectors_done, switch_core_session_get_pool(fs_session)); end: - if (mutex != NULL) - { - switch_mutex_unlock(mutex); - } - return status; + if (mutex != NULL) + { + switch_mutex_unlock(mutex); + } + return status; } static void avmd_session_close(avmd_session_t *s) { - uint8_t idx; - struct avmd_detector *d; - switch_status_t status; + uint8_t idx; + struct avmd_detector *d; + switch_status_t status; - switch_mutex_lock(s->mutex); + switch_mutex_lock(s->mutex); - switch_mutex_lock(s->mutex_detectors_done); - while (avmd_detection_in_progress(s) == 1) { - switch_thread_cond_wait(s->cond_detectors_done, s->mutex_detectors_done); - } - switch_mutex_unlock(s->mutex_detectors_done); + switch_mutex_lock(s->mutex_detectors_done); + while (avmd_detection_in_progress(s) == 1) { + switch_thread_cond_wait(s->cond_detectors_done, s->mutex_detectors_done); + } + switch_mutex_unlock(s->mutex_detectors_done); - idx = 0; - while (idx < (s->settings.detectors_n + s->settings.detectors_lagged_n)) { - d = &s->detectors[idx]; - switch_mutex_lock(d->mutex); - d = &s->detectors[idx]; - d->flag_processing_done = 0; - d->flag_should_exit = 1; - d->samples = 0; - switch_thread_cond_signal(d->cond_start_processing); - switch_mutex_unlock(d->mutex); + idx = 0; + while (idx < (s->settings.detectors_n + s->settings.detectors_lagged_n)) { + d = &s->detectors[idx]; + switch_mutex_lock(d->mutex); + d = &s->detectors[idx]; + d->flag_processing_done = 0; + d->flag_should_exit = 1; + d->samples = 0; + switch_thread_cond_signal(d->cond_start_processing); + switch_mutex_unlock(d->mutex); - switch_thread_join(&status, d->thread); - d->thread = NULL; + switch_thread_join(&status, d->thread); + d->thread = NULL; - switch_mutex_destroy(d->mutex); - switch_thread_cond_destroy(d->cond_start_processing); - ++idx; - } - switch_mutex_unlock(s->mutex); - switch_mutex_destroy(s->mutex_detectors_done); - switch_thread_cond_destroy(s->cond_detectors_done); - switch_mutex_destroy(s->mutex); + switch_mutex_destroy(d->mutex); + switch_thread_cond_destroy(d->cond_start_processing); + ++idx; + } + switch_mutex_unlock(s->mutex); + switch_mutex_destroy(s->mutex_detectors_done); + switch_thread_cond_destroy(s->cond_detectors_done); + switch_mutex_destroy(s->mutex); } /*! \brief The callback function that is called when new audio data becomes available. @@ -565,321 +565,321 @@ static void avmd_session_close(avmd_session_t *s) { * @return The success or failure of the function. */ static switch_bool_t avmd_callback(switch_media_bug_t * bug, void *user_data, switch_abc_type_t type) { - avmd_session_t *avmd_session; - switch_codec_t *read_codec; - switch_codec_t *write_codec; - switch_frame_t *frame; - switch_core_session_t *fs_session; - switch_channel_t *channel = NULL; + avmd_session_t *avmd_session; + switch_codec_t *read_codec; + switch_codec_t *write_codec; + switch_frame_t *frame; + switch_core_session_t *fs_session; + switch_channel_t *channel = NULL; - avmd_session = (avmd_session_t *) user_data; - if (avmd_session == NULL) { - switch_log_printf(SWITCH_CHANNEL_LOG, SWITCH_LOG_ERROR, "No avmd session assigned!\n"); - return SWITCH_FALSE; - } - if ((type != SWITCH_ABC_TYPE_INIT) && (type != SWITCH_ABC_TYPE_CLOSE)) { - switch_mutex_lock(avmd_session->mutex); - } - fs_session = avmd_session->session; - if (fs_session == NULL) { - if (type != SWITCH_ABC_TYPE_INIT) { - switch_mutex_unlock(avmd_session->mutex); - } - switch_log_printf(SWITCH_CHANNEL_LOG, SWITCH_LOG_ERROR, "No FreeSWITCH session assigned!\n"); - return SWITCH_FALSE; - } + avmd_session = (avmd_session_t *) user_data; + if (avmd_session == NULL) { + switch_log_printf(SWITCH_CHANNEL_LOG, SWITCH_LOG_ERROR, "No avmd session assigned!\n"); + return SWITCH_FALSE; + } + if ((type != SWITCH_ABC_TYPE_INIT) && (type != SWITCH_ABC_TYPE_CLOSE)) { + switch_mutex_lock(avmd_session->mutex); + } + fs_session = avmd_session->session; + if (fs_session == NULL) { + if (type != SWITCH_ABC_TYPE_INIT) { + switch_mutex_unlock(avmd_session->mutex); + } + switch_log_printf(SWITCH_CHANNEL_LOG, SWITCH_LOG_ERROR, "No FreeSWITCH session assigned!\n"); + return SWITCH_FALSE; + } - channel = switch_core_session_get_channel(fs_session); - if (channel == NULL) { - switch_log_printf(SWITCH_CHANNEL_LOG, SWITCH_LOG_ERROR, "No channel for FreeSWITCH session!\n"); - return SWITCH_FALSE; - } + channel = switch_core_session_get_channel(fs_session); + if (channel == NULL) { + switch_log_printf(SWITCH_CHANNEL_LOG, SWITCH_LOG_ERROR, "No channel for FreeSWITCH session!\n"); + return SWITCH_FALSE; + } - switch (type) { + switch (type) { - case SWITCH_ABC_TYPE_INIT: - if ((SWITCH_CALL_DIRECTION_OUTBOUND == switch_channel_direction(channel)) && (avmd_session->settings.outbound_channnel == 1)) { - read_codec = switch_core_session_get_read_codec(fs_session); - if (read_codec == NULL) { - switch_log_printf(SWITCH_CHANNEL_SESSION_LOG(fs_session), SWITCH_LOG_WARNING, "No read codec assigned, default session rate to 8000 samples/s\n"); - avmd_session->rate = 8000; - } else { - if (read_codec->implementation == NULL) { - switch_log_printf(SWITCH_CHANNEL_SESSION_LOG(fs_session), SWITCH_LOG_WARNING, "No read codec implementation assigned, default session rate to 8000 samples/s\n"); - avmd_session->rate = 8000; - } else { - avmd_session->rate = read_codec->implementation->samples_per_second; - } - } - } - if ((SWITCH_CALL_DIRECTION_INBOUND == switch_channel_direction(channel)) && (avmd_session->settings.inbound_channnel == 1)) { - write_codec = switch_core_session_get_write_codec(fs_session); - if (write_codec == NULL) { - switch_log_printf(SWITCH_CHANNEL_SESSION_LOG(fs_session), SWITCH_LOG_WARNING, "No write codec assigned, default session rate to 8000 samples/s\n"); - avmd_session->rate = 8000; - } else { - if (write_codec->implementation == NULL) { - switch_log_printf(SWITCH_CHANNEL_SESSION_LOG(fs_session), SWITCH_LOG_WARNING, "No write codec implementation assigned, default session rate to 8000 samples/s\n"); - avmd_session->rate = 8000; - } else { - avmd_session->rate = write_codec->implementation->samples_per_second; - } - } - } - avmd_session->start_time = switch_micro_time_now(); - /* avmd_session->vmd_codec.channels = read_codec->implementation->number_of_channels; */ - switch_log_printf(SWITCH_CHANNEL_SESSION_LOG(fs_session),SWITCH_LOG_INFO, "Avmd session initialized, [%u] samples/s\n", avmd_session->rate); - break; + case SWITCH_ABC_TYPE_INIT: + if ((SWITCH_CALL_DIRECTION_OUTBOUND == switch_channel_direction(channel)) && (avmd_session->settings.outbound_channnel == 1)) { + read_codec = switch_core_session_get_read_codec(fs_session); + if (read_codec == NULL) { + switch_log_printf(SWITCH_CHANNEL_SESSION_LOG(fs_session), SWITCH_LOG_WARNING, "No read codec assigned, default session rate to 8000 samples/s\n"); + avmd_session->rate = 8000; + } else { + if (read_codec->implementation == NULL) { + switch_log_printf(SWITCH_CHANNEL_SESSION_LOG(fs_session), SWITCH_LOG_WARNING, "No read codec implementation assigned, default session rate to 8000 samples/s\n"); + avmd_session->rate = 8000; + } else { + avmd_session->rate = read_codec->implementation->samples_per_second; + } + } + } + if ((SWITCH_CALL_DIRECTION_INBOUND == switch_channel_direction(channel)) && (avmd_session->settings.inbound_channnel == 1)) { + write_codec = switch_core_session_get_write_codec(fs_session); + if (write_codec == NULL) { + switch_log_printf(SWITCH_CHANNEL_SESSION_LOG(fs_session), SWITCH_LOG_WARNING, "No write codec assigned, default session rate to 8000 samples/s\n"); + avmd_session->rate = 8000; + } else { + if (write_codec->implementation == NULL) { + switch_log_printf(SWITCH_CHANNEL_SESSION_LOG(fs_session), SWITCH_LOG_WARNING, "No write codec implementation assigned, default session rate to 8000 samples/s\n"); + avmd_session->rate = 8000; + } else { + avmd_session->rate = write_codec->implementation->samples_per_second; + } + } + } + avmd_session->start_time = switch_micro_time_now(); + /* avmd_session->vmd_codec.channels = read_codec->implementation->number_of_channels; */ + switch_log_printf(SWITCH_CHANNEL_SESSION_LOG(fs_session),SWITCH_LOG_INFO, "Avmd session initialized, [%u] samples/s\n", avmd_session->rate); + break; - case SWITCH_ABC_TYPE_READ_REPLACE: - frame = switch_core_media_bug_get_read_replace_frame(bug); - avmd_process(avmd_session, frame, AVMD_READ_REPLACE); - break; + case SWITCH_ABC_TYPE_READ_REPLACE: + frame = switch_core_media_bug_get_read_replace_frame(bug); + avmd_process(avmd_session, frame, AVMD_READ_REPLACE); + break; - case SWITCH_ABC_TYPE_WRITE_REPLACE: - frame = switch_core_media_bug_get_write_replace_frame(bug); - avmd_process(avmd_session, frame, AVMD_WRITE_REPLACE); - break; + case SWITCH_ABC_TYPE_WRITE_REPLACE: + frame = switch_core_media_bug_get_write_replace_frame(bug); + avmd_process(avmd_session, frame, AVMD_WRITE_REPLACE); + break; - case SWITCH_ABC_TYPE_CLOSE: - avmd_session_close(avmd_session); + case SWITCH_ABC_TYPE_CLOSE: + avmd_session_close(avmd_session); switch_mutex_lock(avmd_globals.mutex); - if (avmd_globals.session_n > 0) { - --avmd_globals.session_n; - } + if (avmd_globals.session_n > 0) { + --avmd_globals.session_n; + } switch_mutex_unlock(avmd_globals.mutex); - break; + break; - default: - break; - } + default: + break; + } - if ((type != SWITCH_ABC_TYPE_INIT) && (type != SWITCH_ABC_TYPE_CLOSE)) { - switch_mutex_unlock(avmd_session->mutex); - } - return SWITCH_TRUE; + if ((type != SWITCH_ABC_TYPE_INIT) && (type != SWITCH_ABC_TYPE_CLOSE)) { + switch_mutex_unlock(avmd_session->mutex); + } + return SWITCH_TRUE; } static switch_status_t avmd_register_all_events(void) { - size_t idx = 0; - const char *e = avmd_events_str[0]; - while (e != NULL) - { - if (switch_event_reserve_subclass(e) != SWITCH_STATUS_SUCCESS) { - switch_log_printf(SWITCH_CHANNEL_LOG, SWITCH_LOG_ERROR, "Couldn't register subclass [%s]!\n", e); - return SWITCH_STATUS_TERM; - } - ++idx; - e = avmd_events_str[idx]; - } - return SWITCH_STATUS_SUCCESS; + size_t idx = 0; + const char *e = avmd_events_str[0]; + while (e != NULL) + { + if (switch_event_reserve_subclass(e) != SWITCH_STATUS_SUCCESS) { + switch_log_printf(SWITCH_CHANNEL_LOG, SWITCH_LOG_ERROR, "Couldn't register subclass [%s]!\n", e); + return SWITCH_STATUS_TERM; + } + ++idx; + e = avmd_events_str[idx]; + } + return SWITCH_STATUS_SUCCESS; } static void avmd_unregister_all_events(void) { - size_t idx = 0; - const char *e = avmd_events_str[0]; - while (e != NULL) - { - switch_event_free_subclass(e); - ++idx; - e = avmd_events_str[idx]; - } - return; + size_t idx = 0; + const char *e = avmd_events_str[0]; + while (e != NULL) + { + switch_event_free_subclass(e); + ++idx; + e = avmd_events_str[idx]; + } + return; } static void avmd_fire_event(enum avmd_event type, switch_core_session_t *fs_s, double freq, double v_freq, double amp, double v_amp, avmd_beep_state_t beep_status, uint8_t info, - switch_time_t detection_start_time, switch_time_t detection_stop_time, switch_time_t start_time, switch_time_t stop_time, uint8_t resolution, uint8_t offset, uint8_t idx) { - int res; - switch_event_t *event; - switch_time_t detection_time, total_time; - switch_status_t status; - switch_event_t *event_copy; - char buf[AVMD_CHAR_BUF_LEN]; + switch_time_t detection_start_time, switch_time_t detection_stop_time, switch_time_t start_time, switch_time_t stop_time, uint8_t resolution, uint8_t offset, uint8_t idx) { + int res; + switch_event_t *event; + switch_time_t detection_time, total_time; + switch_status_t status; + switch_event_t *event_copy; + char buf[AVMD_CHAR_BUF_LEN]; - status = switch_event_create_subclass(&event, SWITCH_EVENT_CUSTOM, avmd_events_str[type]); - if (status != SWITCH_STATUS_SUCCESS) { - return; - } - switch_event_add_header_string(event, SWITCH_STACK_BOTTOM, "Unique-ID", switch_core_session_get_uuid(fs_s)); - switch_event_add_header_string(event, SWITCH_STACK_BOTTOM, "Call-command", "avmd"); - switch (type) - { - case AVMD_EVENT_BEEP: - switch_event_add_header_string(event, SWITCH_STACK_BOTTOM, "Beep-Status", "DETECTED"); - res = snprintf(buf, AVMD_CHAR_BUF_LEN, "%f", freq); - if (res < 0 || res > AVMD_CHAR_BUF_LEN - 1) { - switch_log_printf(SWITCH_CHANNEL_SESSION_LOG(fs_s), SWITCH_LOG_ERROR, "Frequency truncated [%s], [%d] attempted!\n", buf, res); - switch_event_add_header_string(event, SWITCH_STACK_BOTTOM, "Frequency", "ERROR (TRUNCATED)"); - } - switch_event_add_header_string(event, SWITCH_STACK_BOTTOM, "Frequency", buf); + status = switch_event_create_subclass(&event, SWITCH_EVENT_CUSTOM, avmd_events_str[type]); + if (status != SWITCH_STATUS_SUCCESS) { + return; + } + switch_event_add_header_string(event, SWITCH_STACK_BOTTOM, "Unique-ID", switch_core_session_get_uuid(fs_s)); + switch_event_add_header_string(event, SWITCH_STACK_BOTTOM, "Call-command", "avmd"); + switch (type) + { + case AVMD_EVENT_BEEP: + switch_event_add_header_string(event, SWITCH_STACK_BOTTOM, "Beep-Status", "DETECTED"); + res = snprintf(buf, AVMD_CHAR_BUF_LEN, "%f", freq); + if (res < 0 || res > AVMD_CHAR_BUF_LEN - 1) { + switch_log_printf(SWITCH_CHANNEL_SESSION_LOG(fs_s), SWITCH_LOG_ERROR, "Frequency truncated [%s], [%d] attempted!\n", buf, res); + switch_event_add_header_string(event, SWITCH_STACK_BOTTOM, "Frequency", "ERROR (TRUNCATED)"); + } + switch_event_add_header_string(event, SWITCH_STACK_BOTTOM, "Frequency", buf); - res = snprintf(buf, AVMD_CHAR_BUF_LEN, "%f", v_freq); - if (res < 0 || res > AVMD_CHAR_BUF_LEN - 1) { - switch_log_printf(SWITCH_CHANNEL_SESSION_LOG(fs_s), SWITCH_LOG_ERROR, "Error, truncated [%s], [%d] attempeted!\n", buf, res); - switch_event_add_header_string(event, SWITCH_STACK_BOTTOM, "Frequency-variance", "ERROR (TRUNCATED)"); - } - switch_event_add_header_string(event, SWITCH_STACK_BOTTOM, "Frequency-variance", buf); + res = snprintf(buf, AVMD_CHAR_BUF_LEN, "%f", v_freq); + if (res < 0 || res > AVMD_CHAR_BUF_LEN - 1) { + switch_log_printf(SWITCH_CHANNEL_SESSION_LOG(fs_s), SWITCH_LOG_ERROR, "Error, truncated [%s], [%d] attempeted!\n", buf, res); + switch_event_add_header_string(event, SWITCH_STACK_BOTTOM, "Frequency-variance", "ERROR (TRUNCATED)"); + } + switch_event_add_header_string(event, SWITCH_STACK_BOTTOM, "Frequency-variance", buf); - res = snprintf(buf, AVMD_CHAR_BUF_LEN, "%f", amp); - if (res < 0 || res > AVMD_CHAR_BUF_LEN - 1) { - switch_log_printf(SWITCH_CHANNEL_SESSION_LOG(fs_s), SWITCH_LOG_ERROR, "Amplitude truncated [%s], [%d] attempted!\n", buf, res); - switch_event_add_header_string(event, SWITCH_STACK_BOTTOM, "Amplitude", "ERROR (TRUNCATED)"); - } - switch_event_add_header_string(event, SWITCH_STACK_BOTTOM, "Amplitude", buf); + res = snprintf(buf, AVMD_CHAR_BUF_LEN, "%f", amp); + if (res < 0 || res > AVMD_CHAR_BUF_LEN - 1) { + switch_log_printf(SWITCH_CHANNEL_SESSION_LOG(fs_s), SWITCH_LOG_ERROR, "Amplitude truncated [%s], [%d] attempted!\n", buf, res); + switch_event_add_header_string(event, SWITCH_STACK_BOTTOM, "Amplitude", "ERROR (TRUNCATED)"); + } + switch_event_add_header_string(event, SWITCH_STACK_BOTTOM, "Amplitude", buf); - res = snprintf(buf, AVMD_CHAR_BUF_LEN, "%f", v_amp); - if (res < 0 || res > AVMD_CHAR_BUF_LEN - 1) { - switch_log_printf(SWITCH_CHANNEL_SESSION_LOG(fs_s), SWITCH_LOG_ERROR, "Error, truncated [%s], [%d] attempeted!\n", buf, res); - switch_event_add_header_string(event, SWITCH_STACK_BOTTOM, "Amplitude-variance", "ERROR (TRUNCATED)"); - } - switch_event_add_header_string(event, SWITCH_STACK_BOTTOM, "Amplitude-variance", buf); + res = snprintf(buf, AVMD_CHAR_BUF_LEN, "%f", v_amp); + if (res < 0 || res > AVMD_CHAR_BUF_LEN - 1) { + switch_log_printf(SWITCH_CHANNEL_SESSION_LOG(fs_s), SWITCH_LOG_ERROR, "Error, truncated [%s], [%d] attempeted!\n", buf, res); + switch_event_add_header_string(event, SWITCH_STACK_BOTTOM, "Amplitude-variance", "ERROR (TRUNCATED)"); + } + switch_event_add_header_string(event, SWITCH_STACK_BOTTOM, "Amplitude-variance", buf); - detection_time = detection_stop_time - detection_start_time; - res = snprintf(buf, AVMD_CHAR_BUF_LEN, "%" PRId64 "", detection_time); - if (res < 0 || res > AVMD_CHAR_BUF_LEN - 1) { - switch_log_printf(SWITCH_CHANNEL_SESSION_LOG(fs_s), SWITCH_LOG_ERROR, "Detection time truncated [%s], [%d] attempted!\n", buf, res); - switch_event_add_header_string(event, SWITCH_STACK_BOTTOM, "Detection-time", "ERROR (TRUNCATED)"); - } - switch_event_add_header_string(event, SWITCH_STACK_BOTTOM, "Detection-time", buf); + detection_time = detection_stop_time - detection_start_time; + res = snprintf(buf, AVMD_CHAR_BUF_LEN, "%" PRId64 "", detection_time); + if (res < 0 || res > AVMD_CHAR_BUF_LEN - 1) { + switch_log_printf(SWITCH_CHANNEL_SESSION_LOG(fs_s), SWITCH_LOG_ERROR, "Detection time truncated [%s], [%d] attempted!\n", buf, res); + switch_event_add_header_string(event, SWITCH_STACK_BOTTOM, "Detection-time", "ERROR (TRUNCATED)"); + } + switch_event_add_header_string(event, SWITCH_STACK_BOTTOM, "Detection-time", buf); - res = snprintf(buf, AVMD_CHAR_BUF_LEN, "%u", resolution); - if (res < 0 || res > AVMD_CHAR_BUF_LEN - 1) { - switch_log_printf(SWITCH_CHANNEL_SESSION_LOG(fs_s), SWITCH_LOG_ERROR, "Error, truncated [%s], [%d] attempeted!\n", buf, res); - switch_event_add_header_string(event, SWITCH_STACK_BOTTOM, "Detector-resolution", "ERROR (TRUNCATED)"); - } - switch_event_add_header_string(event, SWITCH_STACK_BOTTOM, "Detector-resolution", buf); + res = snprintf(buf, AVMD_CHAR_BUF_LEN, "%u", resolution); + if (res < 0 || res > AVMD_CHAR_BUF_LEN - 1) { + switch_log_printf(SWITCH_CHANNEL_SESSION_LOG(fs_s), SWITCH_LOG_ERROR, "Error, truncated [%s], [%d] attempeted!\n", buf, res); + switch_event_add_header_string(event, SWITCH_STACK_BOTTOM, "Detector-resolution", "ERROR (TRUNCATED)"); + } + switch_event_add_header_string(event, SWITCH_STACK_BOTTOM, "Detector-resolution", buf); - res = snprintf(buf, AVMD_CHAR_BUF_LEN, "%u", offset); - if (res < 0 || res > AVMD_CHAR_BUF_LEN - 1) { - switch_log_printf(SWITCH_CHANNEL_SESSION_LOG(fs_s), SWITCH_LOG_ERROR, "Error, truncated [%s], [%d] attempeted!\n", buf, res); - switch_event_add_header_string(event, SWITCH_STACK_BOTTOM, "Detector-offset", "ERROR (TRUNCATED)"); - } - switch_event_add_header_string(event, SWITCH_STACK_BOTTOM, "Detector-offset", buf); + res = snprintf(buf, AVMD_CHAR_BUF_LEN, "%u", offset); + if (res < 0 || res > AVMD_CHAR_BUF_LEN - 1) { + switch_log_printf(SWITCH_CHANNEL_SESSION_LOG(fs_s), SWITCH_LOG_ERROR, "Error, truncated [%s], [%d] attempeted!\n", buf, res); + switch_event_add_header_string(event, SWITCH_STACK_BOTTOM, "Detector-offset", "ERROR (TRUNCATED)"); + } + switch_event_add_header_string(event, SWITCH_STACK_BOTTOM, "Detector-offset", buf); - res = snprintf(buf, AVMD_CHAR_BUF_LEN, "%u", idx); - if (res < 0 || res > AVMD_CHAR_BUF_LEN - 1) { - switch_log_printf(SWITCH_CHANNEL_SESSION_LOG(fs_s), SWITCH_LOG_ERROR, "Error, truncated [%s], [%d] attempeted!\n", buf, res); - switch_event_add_header_string(event, SWITCH_STACK_BOTTOM, "Detector-index", "ERROR (TRUNCATED)"); - } - switch_event_add_header_string(event, SWITCH_STACK_BOTTOM, "Detector-index", buf); - break; + res = snprintf(buf, AVMD_CHAR_BUF_LEN, "%u", idx); + if (res < 0 || res > AVMD_CHAR_BUF_LEN - 1) { + switch_log_printf(SWITCH_CHANNEL_SESSION_LOG(fs_s), SWITCH_LOG_ERROR, "Error, truncated [%s], [%d] attempeted!\n", buf, res); + switch_event_add_header_string(event, SWITCH_STACK_BOTTOM, "Detector-index", "ERROR (TRUNCATED)"); + } + switch_event_add_header_string(event, SWITCH_STACK_BOTTOM, "Detector-index", buf); + break; - case AVMD_EVENT_SESSION_START: - res = snprintf(buf, AVMD_CHAR_BUF_LEN, "%" PRId64 "", start_time); - if (res < 0 || res > AVMD_CHAR_BUF_LEN - 1) { - switch_log_printf(SWITCH_CHANNEL_SESSION_LOG(fs_s), SWITCH_LOG_ERROR, "Start time truncated [%s], [%d] attempted!\n", buf, res); - switch_event_add_header_string(event, SWITCH_STACK_BOTTOM, "Start-time", "ERROR (TRUNCATED)"); - } - switch_event_add_header_string(event, SWITCH_STACK_BOTTOM, "Start-time", buf); - break; + case AVMD_EVENT_SESSION_START: + res = snprintf(buf, AVMD_CHAR_BUF_LEN, "%" PRId64 "", start_time); + if (res < 0 || res > AVMD_CHAR_BUF_LEN - 1) { + switch_log_printf(SWITCH_CHANNEL_SESSION_LOG(fs_s), SWITCH_LOG_ERROR, "Start time truncated [%s], [%d] attempted!\n", buf, res); + switch_event_add_header_string(event, SWITCH_STACK_BOTTOM, "Start-time", "ERROR (TRUNCATED)"); + } + switch_event_add_header_string(event, SWITCH_STACK_BOTTOM, "Start-time", buf); + break; - case AVMD_EVENT_SESSION_STOP: - switch_event_add_header_string(event, SWITCH_STACK_BOTTOM, "Beep-Status", beep_status == BEEP_DETECTED ? "DETECTED" : "NOTDETECTED"); - if (info == 0) { - switch_event_add_header_string(event, SWITCH_STACK_BOTTOM, "Stop-status", "ERROR (AVMD SESSION OBJECT NOT FOUND IN MEDIA BUG)"); - } - total_time = stop_time - start_time; - res = snprintf(buf, AVMD_CHAR_BUF_LEN, "%" PRId64 "", total_time); - if (res < 0 || res > AVMD_CHAR_BUF_LEN - 1) { - switch_log_printf(SWITCH_CHANNEL_SESSION_LOG(fs_s), SWITCH_LOG_ERROR, "Total time truncated [%s], [%d] attempted!\n", buf, res); - switch_event_add_header_string(event, SWITCH_STACK_BOTTOM, "Total-time", "ERROR (TRUNCATED)"); - } - switch_event_add_header_string(event, SWITCH_STACK_BOTTOM, "Total-time", buf); - break; + case AVMD_EVENT_SESSION_STOP: + switch_event_add_header_string(event, SWITCH_STACK_BOTTOM, "Beep-Status", beep_status == BEEP_DETECTED ? "DETECTED" : "NOTDETECTED"); + if (info == 0) { + switch_event_add_header_string(event, SWITCH_STACK_BOTTOM, "Stop-status", "ERROR (AVMD SESSION OBJECT NOT FOUND IN MEDIA BUG)"); + } + total_time = stop_time - start_time; + res = snprintf(buf, AVMD_CHAR_BUF_LEN, "%" PRId64 "", total_time); + if (res < 0 || res > AVMD_CHAR_BUF_LEN - 1) { + switch_log_printf(SWITCH_CHANNEL_SESSION_LOG(fs_s), SWITCH_LOG_ERROR, "Total time truncated [%s], [%d] attempted!\n", buf, res); + switch_event_add_header_string(event, SWITCH_STACK_BOTTOM, "Total-time", "ERROR (TRUNCATED)"); + } + switch_event_add_header_string(event, SWITCH_STACK_BOTTOM, "Total-time", buf); + break; - default: - switch_event_destroy(&event); - return; - } + default: + switch_event_destroy(&event); + return; + } - if ((switch_event_dup(&event_copy, event)) != SWITCH_STATUS_SUCCESS) { - return; - } + if ((switch_event_dup(&event_copy, event)) != SWITCH_STATUS_SUCCESS) { + return; + } - switch_core_session_queue_event(fs_s, &event); - switch_event_fire(&event_copy); - return; + switch_core_session_queue_event(fs_s, &event); + switch_event_fire(&event_copy); + return; } int avmd_parse_u8_user_input(const char *input, uint8_t *output, uint8_t min, uint8_t max) { - char *pCh; - unsigned long helper; - helper = strtoul(input, &pCh, 10); - if (helper < min || helper > UINT8_MAX || helper > max || (pCh == input) || (*pCh != '\0')) { - return -1; - } - *output = (uint8_t) helper; - return 0; + char *pCh; + unsigned long helper; + helper = strtoul(input, &pCh, 10); + if (helper < min || helper > UINT8_MAX || helper > max || (pCh == input) || (*pCh != '\0')) { + return -1; + } + *output = (uint8_t) helper; + return 0; } int avmd_parse_u16_user_input(const char *input, uint16_t *output, uint16_t min, uint16_t max) { - char *pCh; - unsigned long helper; - if (min > max) { - return -1; - } - helper = strtoul(input, &pCh, 10); - if (helper < min || helper > UINT16_MAX || helper > max || (pCh == input) || (*pCh != '\0')) { - return -1; - } - *output = (uint16_t) helper; - return 0; + char *pCh; + unsigned long helper; + if (min > max) { + return -1; + } + helper = strtoul(input, &pCh, 10); + if (helper < min || helper > UINT16_MAX || helper > max || (pCh == input) || (*pCh != '\0')) { + return -1; + } + *output = (uint16_t) helper; + return 0; } static void avmd_set_xml_default_configuration(switch_mutex_t *mutex) { - if (mutex != NULL) { - switch_mutex_lock(mutex); - } + if (mutex != NULL) { + switch_mutex_lock(mutex); + } - avmd_globals.settings.debug = 0; - avmd_globals.settings.report_status = 1; - avmd_globals.settings.fast_math = 0; - avmd_globals.settings.require_continuous_streak = 1; - avmd_globals.settings.sample_n_continuous_streak = 3; - avmd_globals.settings.sample_n_to_skip = 0; - avmd_globals.settings.require_continuous_streak_amp = 1; - avmd_globals.settings.sample_n_continuous_streak_amp = 3; - avmd_globals.settings.simplified_estimation = 1; - avmd_globals.settings.inbound_channnel = 0; - avmd_globals.settings.outbound_channnel = 1; - avmd_globals.settings.mode = AVMD_DETECT_BOTH; - avmd_globals.settings.detectors_n = 36; - avmd_globals.settings.detectors_lagged_n = 1; + avmd_globals.settings.debug = 0; + avmd_globals.settings.report_status = 1; + avmd_globals.settings.fast_math = 0; + avmd_globals.settings.require_continuous_streak = 1; + avmd_globals.settings.sample_n_continuous_streak = 3; + avmd_globals.settings.sample_n_to_skip = 0; + avmd_globals.settings.require_continuous_streak_amp = 1; + avmd_globals.settings.sample_n_continuous_streak_amp = 3; + avmd_globals.settings.simplified_estimation = 1; + avmd_globals.settings.inbound_channnel = 0; + avmd_globals.settings.outbound_channnel = 1; + avmd_globals.settings.mode = AVMD_DETECT_BOTH; + avmd_globals.settings.detectors_n = 36; + avmd_globals.settings.detectors_lagged_n = 1; - if (mutex != NULL) { - switch_mutex_unlock(avmd_globals.mutex); - } - return; + if (mutex != NULL) { + switch_mutex_unlock(avmd_globals.mutex); + } + return; } static void avmd_set_xml_inbound_configuration(switch_mutex_t *mutex) { - if (mutex != NULL) { - switch_mutex_lock(mutex); - } + if (mutex != NULL) { + switch_mutex_lock(mutex); + } - avmd_globals.settings.inbound_channnel = 1; - avmd_globals.settings.outbound_channnel = 0; + avmd_globals.settings.inbound_channnel = 1; + avmd_globals.settings.outbound_channnel = 0; - if (mutex != NULL) { - switch_mutex_unlock(avmd_globals.mutex); - } - return; + if (mutex != NULL) { + switch_mutex_unlock(avmd_globals.mutex); + } + return; } static void avmd_set_xml_outbound_configuration(switch_mutex_t *mutex) { - if (mutex != NULL) { - switch_mutex_lock(mutex); - } + if (mutex != NULL) { + switch_mutex_lock(mutex); + } - avmd_globals.settings.inbound_channnel = 0; - avmd_globals.settings.outbound_channnel = 1; + avmd_globals.settings.inbound_channnel = 0; + avmd_globals.settings.outbound_channnel = 1; - if (mutex != NULL) { - switch_mutex_unlock(avmd_globals.mutex); - } - return; + if (mutex != NULL) { + switch_mutex_unlock(avmd_globals.mutex); + } + return; } static switch_status_t avmd_load_xml_configuration(switch_mutex_t *mutex) { @@ -1060,249 +1060,249 @@ static switch_status_t avmd_load_xml_configuration(switch_mutex_t *mutex) { } static switch_status_t avmd_load_xml_inbound_configuration(switch_mutex_t *mutex) { - if (avmd_load_xml_configuration(mutex) != SWITCH_STATUS_SUCCESS) { - return SWITCH_STATUS_TERM; - } + if (avmd_load_xml_configuration(mutex) != SWITCH_STATUS_SUCCESS) { + return SWITCH_STATUS_TERM; + } - if (mutex != NULL) { - switch_mutex_lock(mutex); - } + if (mutex != NULL) { + switch_mutex_lock(mutex); + } - avmd_globals.settings.inbound_channnel = 1; - avmd_globals.settings.outbound_channnel = 0; + avmd_globals.settings.inbound_channnel = 1; + avmd_globals.settings.outbound_channnel = 0; - if (mutex != NULL) { - switch_mutex_unlock(avmd_globals.mutex); - } - return SWITCH_STATUS_SUCCESS; + if (mutex != NULL) { + switch_mutex_unlock(avmd_globals.mutex); + } + return SWITCH_STATUS_SUCCESS; } static switch_status_t avmd_load_xml_outbound_configuration(switch_mutex_t *mutex) { - if (avmd_load_xml_configuration(mutex) != SWITCH_STATUS_SUCCESS) { - return SWITCH_STATUS_TERM; - } + if (avmd_load_xml_configuration(mutex) != SWITCH_STATUS_SUCCESS) { + return SWITCH_STATUS_TERM; + } - if (mutex != NULL) { - switch_mutex_lock(mutex); - } + if (mutex != NULL) { + switch_mutex_lock(mutex); + } - avmd_globals.settings.inbound_channnel = 0; - avmd_globals.settings.outbound_channnel = 1; + avmd_globals.settings.inbound_channnel = 0; + avmd_globals.settings.outbound_channnel = 1; - if (mutex != NULL) { - switch_mutex_unlock(avmd_globals.mutex); - } - return SWITCH_STATUS_SUCCESS; + if (mutex != NULL) { + switch_mutex_unlock(avmd_globals.mutex); + } + return SWITCH_STATUS_SUCCESS; } static void avmd_show(switch_stream_handle_t *stream, switch_mutex_t *mutex) { - const char *line = "================================================================================================="; - if (stream == NULL) { - return; - } + const char *line = "================================================================================================="; + if (stream == NULL) { + return; + } - if (mutex != NULL) { - switch_mutex_lock(mutex); - } + if (mutex != NULL) { + switch_mutex_lock(mutex); + } - stream->write_function(stream, "\n\n"); - stream->write_function(stream, "%s\n\n", line); - stream->write_function(stream, "%s\n", "Avmd global settings\n\n"); - stream->write_function(stream, "debug \t%u\n", avmd_globals.settings.debug); - stream->write_function(stream, "report status \t%u\n", avmd_globals.settings.report_status); - stream->write_function(stream, "fast_math \t%u\n", avmd_globals.settings.fast_math); - stream->write_function(stream, "require continuous streak \t%u\n", avmd_globals.settings.require_continuous_streak); - stream->write_function(stream, "sample n continuous streak \t%u\n", avmd_globals.settings.sample_n_continuous_streak); - stream->write_function(stream, "sample n to skip \t%u\n", avmd_globals.settings.sample_n_to_skip); - stream->write_function(stream, "require continuous streak amp \t%u\n", avmd_globals.settings.require_continuous_streak_amp); - stream->write_function(stream, "sample n continuous streak amp \t%u\n", avmd_globals.settings.sample_n_continuous_streak_amp); - stream->write_function(stream, "simplified estimation \t%u\n", avmd_globals.settings.simplified_estimation); - stream->write_function(stream, "inbound channel \t%u\n", avmd_globals.settings.inbound_channnel); - stream->write_function(stream, "outbound channel \t%u\n", avmd_globals.settings.outbound_channnel); - stream->write_function(stream, "detection mode \t%u\n", avmd_globals.settings.mode); - stream->write_function(stream, "sessions \t%"PRId64"\n", avmd_globals.session_n); - stream->write_function(stream, "detectors n \t%u\n", avmd_globals.settings.detectors_n); - stream->write_function(stream, "detectors lagged n \t%u\n", avmd_globals.settings.detectors_lagged_n); - stream->write_function(stream, "\n\n"); + stream->write_function(stream, "\n\n"); + stream->write_function(stream, "%s\n\n", line); + stream->write_function(stream, "%s\n", "Avmd global settings\n\n"); + stream->write_function(stream, "debug \t%u\n", avmd_globals.settings.debug); + stream->write_function(stream, "report status \t%u\n", avmd_globals.settings.report_status); + stream->write_function(stream, "fast_math \t%u\n", avmd_globals.settings.fast_math); + stream->write_function(stream, "require continuous streak \t%u\n", avmd_globals.settings.require_continuous_streak); + stream->write_function(stream, "sample n continuous streak \t%u\n", avmd_globals.settings.sample_n_continuous_streak); + stream->write_function(stream, "sample n to skip \t%u\n", avmd_globals.settings.sample_n_to_skip); + stream->write_function(stream, "require continuous streak amp \t%u\n", avmd_globals.settings.require_continuous_streak_amp); + stream->write_function(stream, "sample n continuous streak amp \t%u\n", avmd_globals.settings.sample_n_continuous_streak_amp); + stream->write_function(stream, "simplified estimation \t%u\n", avmd_globals.settings.simplified_estimation); + stream->write_function(stream, "inbound channel \t%u\n", avmd_globals.settings.inbound_channnel); + stream->write_function(stream, "outbound channel \t%u\n", avmd_globals.settings.outbound_channnel); + stream->write_function(stream, "detection mode \t%u\n", avmd_globals.settings.mode); + stream->write_function(stream, "sessions \t%"PRId64"\n", avmd_globals.session_n); + stream->write_function(stream, "detectors n \t%u\n", avmd_globals.settings.detectors_n); + stream->write_function(stream, "detectors lagged n \t%u\n", avmd_globals.settings.detectors_lagged_n); + stream->write_function(stream, "\n\n"); - if (mutex != NULL) { - switch_mutex_unlock(mutex); - } + if (mutex != NULL) { + switch_mutex_unlock(mutex); + } } SWITCH_MODULE_LOAD_FUNCTION(mod_avmd_load) { #ifndef WIN32 - char err[150]; - int ret; + char err[150]; + int ret; #endif - switch_application_interface_t *app_interface; - switch_api_interface_t *api_interface; - /* connect my internal structure to the blank pointer passed to me */ - *module_interface = switch_loadable_module_create_module_interface(pool, modname); + switch_application_interface_t *app_interface; + switch_api_interface_t *api_interface; + /* connect my internal structure to the blank pointer passed to me */ + *module_interface = switch_loadable_module_create_module_interface(pool, modname); - if (avmd_register_all_events() != SWITCH_STATUS_SUCCESS) { - switch_log_printf(SWITCH_CHANNEL_LOG, SWITCH_LOG_ERROR, "Couldn't register avmd events!\n"); - return SWITCH_STATUS_TERM; - } + if (avmd_register_all_events() != SWITCH_STATUS_SUCCESS) { + switch_log_printf(SWITCH_CHANNEL_LOG, SWITCH_LOG_ERROR, "Couldn't register avmd events!\n"); + return SWITCH_STATUS_TERM; + } - memset(&avmd_globals, 0, sizeof(avmd_globals)); - if (pool == NULL) { - switch_log_printf(SWITCH_CHANNEL_LOG, SWITCH_LOG_ERROR, "No memory pool assigned!\n"); - return SWITCH_STATUS_TERM; - } - switch_mutex_init(&avmd_globals.mutex, SWITCH_MUTEX_NESTED, pool); - avmd_globals.pool = pool; + memset(&avmd_globals, 0, sizeof(avmd_globals)); + if (pool == NULL) { + switch_log_printf(SWITCH_CHANNEL_LOG, SWITCH_LOG_ERROR, "No memory pool assigned!\n"); + return SWITCH_STATUS_TERM; + } + switch_mutex_init(&avmd_globals.mutex, SWITCH_MUTEX_NESTED, pool); + avmd_globals.pool = pool; - if (avmd_load_xml_configuration(NULL) != SWITCH_STATUS_SUCCESS) { - switch_log_printf(SWITCH_CHANNEL_LOG, SWITCH_LOG_ERROR, "Couldn't load XML configuration! Loading default settings\n"); - avmd_set_xml_default_configuration(NULL); - } + if (avmd_load_xml_configuration(NULL) != SWITCH_STATUS_SUCCESS) { + switch_log_printf(SWITCH_CHANNEL_LOG, SWITCH_LOG_ERROR, "Couldn't load XML configuration! Loading default settings\n"); + avmd_set_xml_default_configuration(NULL); + } - if ((switch_event_bind(modname, SWITCH_EVENT_RELOADXML, NULL, avmd_reloadxml_event_handler, NULL) != SWITCH_STATUS_SUCCESS)) { - switch_log_printf(SWITCH_CHANNEL_LOG, SWITCH_LOG_ERROR, "Couldn't bind our reloadxml handler! Module will not react to changes made in XML configuration\n"); - /* Not so severe to prevent further loading, well - it depends, anyway */ - } + if ((switch_event_bind(modname, SWITCH_EVENT_RELOADXML, NULL, avmd_reloadxml_event_handler, NULL) != SWITCH_STATUS_SUCCESS)) { + switch_log_printf(SWITCH_CHANNEL_LOG, SWITCH_LOG_ERROR, "Couldn't bind our reloadxml handler! Module will not react to changes made in XML configuration\n"); + /* Not so severe to prevent further loading, well - it depends, anyway */ + } #ifndef WIN32 - if (avmd_globals.settings.fast_math == 1) { - ret = init_fast_acosf(); - if (ret != 0) { - strerror_r(errno, err, 150); - switch (ret) { + if (avmd_globals.settings.fast_math == 1) { + ret = init_fast_acosf(); + if (ret != 0) { + strerror_r(errno, err, 150); + switch (ret) { - case -1: - switch_log_printf(SWITCH_CHANNEL_LOG, SWITCH_LOG_ERROR, "Can't access file [%s], error [%s]\n", ACOS_TABLE_FILENAME, err); - break; - case -2: - switch_log_printf(SWITCH_CHANNEL_LOG, SWITCH_LOG_ERROR, "Error creating file [%s], error [%s]\n", ACOS_TABLE_FILENAME, err); - break; - case -3: - switch_log_printf(SWITCH_CHANNEL_LOG, SWITCH_LOG_ERROR, "Access rights are OK but can't open file [%s], error [%s]\n", ACOS_TABLE_FILENAME, err); - break; - case -4: - switch_log_printf(SWITCH_CHANNEL_LOG, SWITCH_LOG_ERROR, "Access rights are OK but can't mmap file [%s], error [%s]\n",ACOS_TABLE_FILENAME, err); - break; - default: - switch_log_printf(SWITCH_CHANNEL_LOG,SWITCH_LOG_ERROR, "Unknown error [%d] while initializing fast cos table [%s], errno [%s]\n", ret, ACOS_TABLE_FILENAME, err); - return SWITCH_STATUS_TERM; - } - return SWITCH_STATUS_TERM; - } else - switch_log_printf(SWITCH_CHANNEL_LOG, SWITCH_LOG_NOTICE, "Advanced voicemail detection: fast math enabled, arc cosine table is [%s]\n", ACOS_TABLE_FILENAME); - } + case -1: + switch_log_printf(SWITCH_CHANNEL_LOG, SWITCH_LOG_ERROR, "Can't access file [%s], error [%s]\n", ACOS_TABLE_FILENAME, err); + break; + case -2: + switch_log_printf(SWITCH_CHANNEL_LOG, SWITCH_LOG_ERROR, "Error creating file [%s], error [%s]\n", ACOS_TABLE_FILENAME, err); + break; + case -3: + switch_log_printf(SWITCH_CHANNEL_LOG, SWITCH_LOG_ERROR, "Access rights are OK but can't open file [%s], error [%s]\n", ACOS_TABLE_FILENAME, err); + break; + case -4: + switch_log_printf(SWITCH_CHANNEL_LOG, SWITCH_LOG_ERROR, "Access rights are OK but can't mmap file [%s], error [%s]\n",ACOS_TABLE_FILENAME, err); + break; + default: + switch_log_printf(SWITCH_CHANNEL_LOG,SWITCH_LOG_ERROR, "Unknown error [%d] while initializing fast cos table [%s], errno [%s]\n", ret, ACOS_TABLE_FILENAME, err); + return SWITCH_STATUS_TERM; + } + return SWITCH_STATUS_TERM; + } else + switch_log_printf(SWITCH_CHANNEL_LOG, SWITCH_LOG_NOTICE, "Advanced voicemail detection: fast math enabled, arc cosine table is [%s]\n", ACOS_TABLE_FILENAME); + } #endif - SWITCH_ADD_APP(app_interface, "avmd_start","Start avmd detection", "Start avmd detection", avmd_start_app, "", SAF_NONE); - SWITCH_ADD_APP(app_interface, "avmd_stop","Stop avmd detection", "Stop avmd detection", avmd_stop_app, "", SAF_NONE); - SWITCH_ADD_APP(app_interface, "avmd","Beep detection", "Advanced detection of voicemail beeps", avmd_start_function, AVMD_SYNTAX, SAF_NONE); + SWITCH_ADD_APP(app_interface, "avmd_start","Start avmd detection", "Start avmd detection", avmd_start_app, "", SAF_NONE); + SWITCH_ADD_APP(app_interface, "avmd_stop","Stop avmd detection", "Stop avmd detection", avmd_stop_app, "", SAF_NONE); + SWITCH_ADD_APP(app_interface, "avmd","Beep detection", "Advanced detection of voicemail beeps", avmd_start_function, AVMD_SYNTAX, SAF_NONE); - SWITCH_ADD_API(api_interface, "avmd", "Voicemail beep detection", avmd_api_main, AVMD_SYNTAX); + SWITCH_ADD_API(api_interface, "avmd", "Voicemail beep detection", avmd_api_main, AVMD_SYNTAX); - switch_console_set_complete("add avmd ::console::list_uuid ::[start:stop"); - switch_console_set_complete("add avmd set inbound"); /* set inbound = 1, outbound = 0 */ - switch_console_set_complete("add avmd set outbound"); /* set inbound = 0, outbound = 1 */ - switch_console_set_complete("add avmd set default"); /* restore to factory settings */ - switch_console_set_complete("add avmd load inbound"); /* reload + set inbound */ - switch_console_set_complete("add avmd load outbound"); /* reload + set outbound */ - switch_console_set_complete("add avmd reload"); /* reload XML (it loads from FS installation - * folder, not module's conf/autoload_configs */ - switch_console_set_complete("add avmd show"); + switch_console_set_complete("add avmd ::console::list_uuid ::[start:stop"); + switch_console_set_complete("add avmd set inbound"); /* set inbound = 1, outbound = 0 */ + switch_console_set_complete("add avmd set outbound"); /* set inbound = 0, outbound = 1 */ + switch_console_set_complete("add avmd set default"); /* restore to factory settings */ + switch_console_set_complete("add avmd load inbound"); /* reload + set inbound */ + switch_console_set_complete("add avmd load outbound"); /* reload + set outbound */ + switch_console_set_complete("add avmd reload"); /* reload XML (it loads from FS installation + * folder, not module's conf/autoload_configs */ + switch_console_set_complete("add avmd show"); - switch_log_printf(SWITCH_CHANNEL_LOG, SWITCH_LOG_NOTICE, "Advanced voicemail detection enabled\n"); + switch_log_printf(SWITCH_CHANNEL_LOG, SWITCH_LOG_NOTICE, "Advanced voicemail detection enabled\n"); - return SWITCH_STATUS_SUCCESS; /* indicate that the module should continue to be loaded */ + return SWITCH_STATUS_SUCCESS; /* indicate that the module should continue to be loaded */ } void avmd_config_dump(avmd_session_t *s) { - struct avmd_settings *settings; + struct avmd_settings *settings; - if (s == NULL) { - return; - } - settings = &s->settings; - switch_log_printf(SWITCH_CHANNEL_SESSION_LOG(s->session), SWITCH_LOG_INFO, "Avmd dynamic configuration: debug [%u], report_status [%u], fast_math [%u]," - " require_continuous_streak [%u], sample_n_continuous_streak [%u], sample_n_to_skip [%u], require_continuous_streak_amp [%u], sample_n_continuous_streak_amp [%u]," - " simplified_estimation [%u], inbound_channel [%u], outbound_channel [%u], detection_mode [%u], detectors_n [%u], detectors_lagged_n [%u]\n", - settings->debug, settings->report_status, settings->fast_math, settings->require_continuous_streak, settings->sample_n_continuous_streak, - settings->sample_n_to_skip, settings->require_continuous_streak_amp, settings->sample_n_continuous_streak_amp, - settings->simplified_estimation, settings->inbound_channnel, settings->outbound_channnel, settings->mode, settings->detectors_n, settings->detectors_lagged_n); - return; + if (s == NULL) { + return; + } + settings = &s->settings; + switch_log_printf(SWITCH_CHANNEL_SESSION_LOG(s->session), SWITCH_LOG_INFO, "Avmd dynamic configuration: debug [%u], report_status [%u], fast_math [%u]," + " require_continuous_streak [%u], sample_n_continuous_streak [%u], sample_n_to_skip [%u], require_continuous_streak_amp [%u], sample_n_continuous_streak_amp [%u]," + " simplified_estimation [%u], inbound_channel [%u], outbound_channel [%u], detection_mode [%u], detectors_n [%u], detectors_lagged_n [%u]\n", + settings->debug, settings->report_status, settings->fast_math, settings->require_continuous_streak, settings->sample_n_continuous_streak, + settings->sample_n_to_skip, settings->require_continuous_streak_amp, settings->sample_n_continuous_streak_amp, + settings->simplified_estimation, settings->inbound_channnel, settings->outbound_channnel, settings->mode, settings->detectors_n, settings->detectors_lagged_n); + return; } static switch_status_t avmd_parse_cmd_data_one_entry(char *candidate, struct avmd_settings *settings) { - char *candidate_parsed[3]; - int argc; - const char *key; - const char *val; + char *candidate_parsed[3]; + int argc; + const char *key; + const char *val; - if (settings == NULL) { - return SWITCH_STATUS_TERM; - } - if (candidate == NULL) { - return SWITCH_STATUS_NOOP; - } + if (settings == NULL) { + return SWITCH_STATUS_TERM; + } + if (candidate == NULL) { + return SWITCH_STATUS_NOOP; + } - argc = switch_separate_string(candidate, '=', candidate_parsed, (sizeof(candidate_parsed) / sizeof(candidate_parsed[0]))); - if (argc > 2) { /* currently we accept only option=value syntax */ - return SWITCH_STATUS_IGNORE; - } + argc = switch_separate_string(candidate, '=', candidate_parsed, (sizeof(candidate_parsed) / sizeof(candidate_parsed[0]))); + if (argc > 2) { /* currently we accept only option=value syntax */ + return SWITCH_STATUS_IGNORE; + } - /* this may be option parameter if valid */ - key = candidate_parsed[0]; /* option name */ - if (zstr(key)) { /* empty key */ - return SWITCH_STATUS_NOT_INITALIZED; - } - val = candidate_parsed[1]; /* value of the option: whole string starting at 1 past the '=' */ - if (zstr(val)) { /* nothing after "=" found, empty value */ - return SWITCH_STATUS_MORE_DATA; - } - /* candidate string has "=" somewhere in the middle and some value, - * try to find what option it is by comparing at most given number of bytes */ - if (!strcmp(key, "debug")) { - settings->debug = (uint8_t) switch_true(val); - } else if (!strcmp(key, "report_status")) { - settings->report_status = (uint8_t) switch_true(val); - } else if (!strcmp(key, "fast_math")) { - settings->fast_math = (uint8_t) switch_true(val); - } else if (!strcmp(key, "require_continuous_streak")) { - settings->require_continuous_streak = (uint8_t) switch_true(val); - } else if (!strcmp(key, "sample_n_continuous_streak")) { - if(avmd_parse_u16_user_input(val, &settings->sample_n_continuous_streak, 0, UINT16_MAX) == -1) { - return SWITCH_STATUS_FALSE; - } - } else if (!strcmp(key, "sample_n_to_skip")) { - if(avmd_parse_u16_user_input(val, &settings->sample_n_to_skip, 0, UINT16_MAX) == -1) { - return SWITCH_STATUS_FALSE; - } - } else if (!strcmp(key, "require_continuous_streak_amp")) { - settings->require_continuous_streak_amp = (uint8_t) switch_true(val); - } else if (!strcmp(key, "sample_n_continuous_streak_amp")) { - if(avmd_parse_u16_user_input(val, &settings->sample_n_continuous_streak_amp, 0, UINT16_MAX) == -1) { - return SWITCH_STATUS_FALSE; - } - } else if (!strcmp(key, "simplified_estimation")) { - settings->simplified_estimation = (uint8_t) switch_true(val); - } else if (!strcmp(key, "inbound_channel")) { - settings->inbound_channnel = (uint8_t) switch_true(val); - } else if (!strcmp(key, "outbound_channel")) { - settings->outbound_channnel = (uint8_t) switch_true(val); - } else if (!strcmp(key, "detection_mode")) { - if(avmd_parse_u8_user_input(val, (uint8_t*)&settings->mode, 0, 2) == -1) { - return SWITCH_STATUS_FALSE; - } - } else if (!strcmp(key, "detectors_n")) { - if(avmd_parse_u8_user_input(val, &settings->detectors_n, 0, UINT8_MAX) == -1) { - return SWITCH_STATUS_FALSE; - } - } else if (!strcmp(key, "detectors_lagged_n")) { - if(avmd_parse_u8_user_input(val, &settings->detectors_lagged_n, 0, UINT8_MAX) == -1) { - return SWITCH_STATUS_FALSE; - } - } else { - return SWITCH_STATUS_NOTFOUND; - } - return SWITCH_STATUS_SUCCESS; + /* this may be option parameter if valid */ + key = candidate_parsed[0]; /* option name */ + if (zstr(key)) { /* empty key */ + return SWITCH_STATUS_NOT_INITALIZED; + } + val = candidate_parsed[1]; /* value of the option: whole string starting at 1 past the '=' */ + if (zstr(val)) { /* nothing after "=" found, empty value */ + return SWITCH_STATUS_MORE_DATA; + } + /* candidate string has "=" somewhere in the middle and some value, + * try to find what option it is by comparing at most given number of bytes */ + if (!strcmp(key, "debug")) { + settings->debug = (uint8_t) switch_true(val); + } else if (!strcmp(key, "report_status")) { + settings->report_status = (uint8_t) switch_true(val); + } else if (!strcmp(key, "fast_math")) { + settings->fast_math = (uint8_t) switch_true(val); + } else if (!strcmp(key, "require_continuous_streak")) { + settings->require_continuous_streak = (uint8_t) switch_true(val); + } else if (!strcmp(key, "sample_n_continuous_streak")) { + if(avmd_parse_u16_user_input(val, &settings->sample_n_continuous_streak, 0, UINT16_MAX) == -1) { + return SWITCH_STATUS_FALSE; + } + } else if (!strcmp(key, "sample_n_to_skip")) { + if(avmd_parse_u16_user_input(val, &settings->sample_n_to_skip, 0, UINT16_MAX) == -1) { + return SWITCH_STATUS_FALSE; + } + } else if (!strcmp(key, "require_continuous_streak_amp")) { + settings->require_continuous_streak_amp = (uint8_t) switch_true(val); + } else if (!strcmp(key, "sample_n_continuous_streak_amp")) { + if(avmd_parse_u16_user_input(val, &settings->sample_n_continuous_streak_amp, 0, UINT16_MAX) == -1) { + return SWITCH_STATUS_FALSE; + } + } else if (!strcmp(key, "simplified_estimation")) { + settings->simplified_estimation = (uint8_t) switch_true(val); + } else if (!strcmp(key, "inbound_channel")) { + settings->inbound_channnel = (uint8_t) switch_true(val); + } else if (!strcmp(key, "outbound_channel")) { + settings->outbound_channnel = (uint8_t) switch_true(val); + } else if (!strcmp(key, "detection_mode")) { + if(avmd_parse_u8_user_input(val, (uint8_t*)&settings->mode, 0, 2) == -1) { + return SWITCH_STATUS_FALSE; + } + } else if (!strcmp(key, "detectors_n")) { + if(avmd_parse_u8_user_input(val, &settings->detectors_n, 0, UINT8_MAX) == -1) { + return SWITCH_STATUS_FALSE; + } + } else if (!strcmp(key, "detectors_lagged_n")) { + if(avmd_parse_u8_user_input(val, &settings->detectors_lagged_n, 0, UINT8_MAX) == -1) { + return SWITCH_STATUS_FALSE; + } + } else { + return SWITCH_STATUS_NOTFOUND; + } + return SWITCH_STATUS_SUCCESS; } /* RCU style: reads, copies and then updates only if everything is fine, @@ -1310,740 +1310,740 @@ static switch_status_t avmd_parse_cmd_data_one_entry(char *candidate, struct avm * are updated accordingly to @cmd_data, if SWITCH_STATUS_FALSE then * parsing error occurred and avmd session is left untouched */ static switch_status_t avmd_parse_cmd_data(avmd_session_t *s, const char *cmd_data, enum avmd_app app) { - char *mydata; - struct avmd_settings settings; - int argc = 0, idx; - char *argv[AVMD_PARAMS_APP_MAX * 2] = { 0 }; - switch_status_t status = SWITCH_STATUS_SUCCESS; + char *mydata; + struct avmd_settings settings; + int argc = 0, idx; + char *argv[AVMD_PARAMS_APP_MAX * 2] = { 0 }; + switch_status_t status = SWITCH_STATUS_SUCCESS; - if (s == NULL) { - return SWITCH_STATUS_NOOP; - } + if (s == NULL) { + return SWITCH_STATUS_NOOP; + } - memcpy(&settings, &avmd_globals.settings, sizeof (struct avmd_settings)); /* copy globally set settings first */ - if (zstr(cmd_data)) { - goto end_copy; - } + memcpy(&settings, &avmd_globals.settings, sizeof (struct avmd_settings)); /* copy globally set settings first */ + if (zstr(cmd_data)) { + goto end_copy; + } - switch (app) { + switch (app) { - case AVMD_APP_START_APP: - /* try to parse settings */ - mydata = switch_core_session_strdup(s->session, cmd_data); - argc = switch_separate_string(mydata, ',', argv, (sizeof(argv) / sizeof(argv[0]))); - if (argc < AVMD_PARAMS_APP_START_MIN || argc > AVMD_PARAMS_APP_START_MAX) { - switch_log_printf(SWITCH_CHANNEL_SESSION_LOG(s->session), SWITCH_LOG_ERROR, - "Syntax Error, avmd_start APP takes [%u] to [%u] parameters\n", - AVMD_PARAMS_APP_START_MIN, AVMD_PARAMS_APP_START_MAX); - switch_goto_status(SWITCH_STATUS_MORE_DATA, fail); - } - /* iterate over params, check if they mean something to us, set */ - idx = 0; - while (idx < argc) { - switch_assert(argv[idx]); - status = avmd_parse_cmd_data_one_entry(argv[idx], &settings); - if (status != SWITCH_STATUS_SUCCESS) { - if (argv[idx]) { - switch_log_printf(SWITCH_CHANNEL_SESSION_LOG(s->session), SWITCH_LOG_ERROR, - "Error parsing option [%d] [%s]\n", idx + 1, argv[idx]); /* idx + 1 to report option 0 as 1 for users convenience */ - } - switch (status) - { - case SWITCH_STATUS_TERM: - switch_log_printf(SWITCH_CHANNEL_SESSION_LOG(s->session), SWITCH_LOG_ERROR, - "NULL settings struct passed to parser\n"); - break; - case SWITCH_STATUS_NOOP: - switch_log_printf(SWITCH_CHANNEL_SESSION_LOG(s->session), SWITCH_LOG_ERROR, - "NULL settings string passed to parser\n"); - break; - case SWITCH_STATUS_IGNORE: - switch_log_printf(SWITCH_CHANNEL_SESSION_LOG(s->session), SWITCH_LOG_ERROR, - "Syntax error. Currently we accept only option=value syntax\n"); - break; - case SWITCH_STATUS_NOT_INITALIZED: - switch_log_printf(SWITCH_CHANNEL_SESSION_LOG(s->session), SWITCH_LOG_ERROR, - "Syntax error. No key specified\n"); - break; - case SWITCH_STATUS_MORE_DATA: - switch_log_printf(SWITCH_CHANNEL_SESSION_LOG(s->session), SWITCH_LOG_ERROR, - "Syntax error. No value for the key? Currently we accept only option=value syntax\n"); - break; - case SWITCH_STATUS_FALSE: - switch_log_printf(SWITCH_CHANNEL_SESSION_LOG(s->session), SWITCH_LOG_ERROR, - "Bad value for this option\n"); - break; - case SWITCH_STATUS_NOTFOUND: - switch_log_printf(SWITCH_CHANNEL_SESSION_LOG(s->session), SWITCH_LOG_ERROR, - "Option not found. Please check option name is correct\n"); - break; - default: - break; - } - status = SWITCH_STATUS_FALSE; - goto fail; - } - ++idx; - } - /* OK */ - goto end_copy; - default: - switch_log_printf(SWITCH_CHANNEL_SESSION_LOG(s->session), SWITCH_LOG_ERROR, "There is no app with index [%u] for avmd\n", app); - switch_goto_status(SWITCH_STATUS_NOTFOUND, fail); - } + case AVMD_APP_START_APP: + /* try to parse settings */ + mydata = switch_core_session_strdup(s->session, cmd_data); + argc = switch_separate_string(mydata, ',', argv, (sizeof(argv) / sizeof(argv[0]))); + if (argc < AVMD_PARAMS_APP_START_MIN || argc > AVMD_PARAMS_APP_START_MAX) { + switch_log_printf(SWITCH_CHANNEL_SESSION_LOG(s->session), SWITCH_LOG_ERROR, + "Syntax Error, avmd_start APP takes [%u] to [%u] parameters\n", + AVMD_PARAMS_APP_START_MIN, AVMD_PARAMS_APP_START_MAX); + switch_goto_status(SWITCH_STATUS_MORE_DATA, fail); + } + /* iterate over params, check if they mean something to us, set */ + idx = 0; + while (idx < argc) { + switch_assert(argv[idx]); + status = avmd_parse_cmd_data_one_entry(argv[idx], &settings); + if (status != SWITCH_STATUS_SUCCESS) { + if (argv[idx]) { + switch_log_printf(SWITCH_CHANNEL_SESSION_LOG(s->session), SWITCH_LOG_ERROR, + "Error parsing option [%d] [%s]\n", idx + 1, argv[idx]); /* idx + 1 to report option 0 as 1 for users convenience */ + } + switch (status) + { + case SWITCH_STATUS_TERM: + switch_log_printf(SWITCH_CHANNEL_SESSION_LOG(s->session), SWITCH_LOG_ERROR, + "NULL settings struct passed to parser\n"); + break; + case SWITCH_STATUS_NOOP: + switch_log_printf(SWITCH_CHANNEL_SESSION_LOG(s->session), SWITCH_LOG_ERROR, + "NULL settings string passed to parser\n"); + break; + case SWITCH_STATUS_IGNORE: + switch_log_printf(SWITCH_CHANNEL_SESSION_LOG(s->session), SWITCH_LOG_ERROR, + "Syntax error. Currently we accept only option=value syntax\n"); + break; + case SWITCH_STATUS_NOT_INITALIZED: + switch_log_printf(SWITCH_CHANNEL_SESSION_LOG(s->session), SWITCH_LOG_ERROR, + "Syntax error. No key specified\n"); + break; + case SWITCH_STATUS_MORE_DATA: + switch_log_printf(SWITCH_CHANNEL_SESSION_LOG(s->session), SWITCH_LOG_ERROR, + "Syntax error. No value for the key? Currently we accept only option=value syntax\n"); + break; + case SWITCH_STATUS_FALSE: + switch_log_printf(SWITCH_CHANNEL_SESSION_LOG(s->session), SWITCH_LOG_ERROR, + "Bad value for this option\n"); + break; + case SWITCH_STATUS_NOTFOUND: + switch_log_printf(SWITCH_CHANNEL_SESSION_LOG(s->session), SWITCH_LOG_ERROR, + "Option not found. Please check option name is correct\n"); + break; + default: + break; + } + status = SWITCH_STATUS_FALSE; + goto fail; + } + ++idx; + } + /* OK */ + goto end_copy; + default: + switch_log_printf(SWITCH_CHANNEL_SESSION_LOG(s->session), SWITCH_LOG_ERROR, "There is no app with index [%u] for avmd\n", app); + switch_goto_status(SWITCH_STATUS_NOTFOUND, fail); + } end_copy: - memcpy(&s->settings, &settings, sizeof (struct avmd_settings)); /* commit the change */ - return SWITCH_STATUS_SUCCESS; + memcpy(&s->settings, &settings, sizeof (struct avmd_settings)); /* commit the change */ + return SWITCH_STATUS_SUCCESS; fail: - return status; + return status; } SWITCH_STANDARD_APP(avmd_start_app) { - switch_media_bug_t *bug = NULL; - switch_status_t status = SWITCH_STATUS_FALSE; - switch_channel_t *channel = NULL; - avmd_session_t *avmd_session = NULL; - switch_core_media_flag_t flags = 0; + switch_media_bug_t *bug = NULL; + switch_status_t status = SWITCH_STATUS_FALSE; + switch_channel_t *channel = NULL; + avmd_session_t *avmd_session = NULL; + switch_core_media_flag_t flags = 0; const char *direction = "NO DIRECTION"; uint8_t report = 0; - if (session == NULL) { - switch_log_printf(SWITCH_CHANNEL_SESSION_LOG(session), SWITCH_LOG_ERROR, "BUGGG. FreeSWITCH session is NULL! Please report to developers\n"); - return; - } + if (session == NULL) { + switch_log_printf(SWITCH_CHANNEL_SESSION_LOG(session), SWITCH_LOG_ERROR, "BUGGG. FreeSWITCH session is NULL! Please report to developers\n"); + return; + } - /* Get current channel of the session to tag the session. This indicates that our module is present - * At this moment this cannot return NULL, it will either succeed or assert failed, but we make ourself secure anyway */ - channel = switch_core_session_get_channel(session); - if (channel == NULL) { - switch_log_printf(SWITCH_CHANNEL_SESSION_LOG(session), SWITCH_LOG_ERROR, "BUGGG. No channel for FreeSWITCH session! Please report this to the developers.\n"); - goto end; - } + /* Get current channel of the session to tag the session. This indicates that our module is present + * At this moment this cannot return NULL, it will either succeed or assert failed, but we make ourself secure anyway */ + channel = switch_core_session_get_channel(session); + if (channel == NULL) { + switch_log_printf(SWITCH_CHANNEL_SESSION_LOG(session), SWITCH_LOG_ERROR, "BUGGG. No channel for FreeSWITCH session! Please report this to the developers.\n"); + goto end; + } - bug = (switch_media_bug_t *) switch_channel_get_private(channel, "_avmd_"); /* Is this channel already set? */ - if (bug != NULL) { /* We have already started */ - switch_log_printf(SWITCH_CHANNEL_SESSION_LOG(session), SWITCH_LOG_ERROR, "Avmd already started!\n"); - return; - } + bug = (switch_media_bug_t *) switch_channel_get_private(channel, "_avmd_"); /* Is this channel already set? */ + if (bug != NULL) { /* We have already started */ + switch_log_printf(SWITCH_CHANNEL_SESSION_LOG(session), SWITCH_LOG_ERROR, "Avmd already started!\n"); + return; + } - /* Allocate memory attached to this FreeSWITCH session for use in the callback routine and to store state information */ - avmd_session = (avmd_session_t *) switch_core_session_alloc(session, sizeof(avmd_session_t)); - if (avmd_session == NULL) { - switch_log_printf(SWITCH_CHANNEL_SESSION_LOG(session), SWITCH_LOG_ERROR, "Can't allocate memory for avmd session!\n"); - status = SWITCH_STATUS_FALSE; - goto end; - } - avmd_session->session = session; + /* Allocate memory attached to this FreeSWITCH session for use in the callback routine and to store state information */ + avmd_session = (avmd_session_t *) switch_core_session_alloc(session, sizeof(avmd_session_t)); + if (avmd_session == NULL) { + switch_log_printf(SWITCH_CHANNEL_SESSION_LOG(session), SWITCH_LOG_ERROR, "Can't allocate memory for avmd session!\n"); + status = SWITCH_STATUS_FALSE; + goto end; + } + avmd_session->session = session; - status = avmd_parse_cmd_data(avmd_session, data, AVMD_APP_START_APP); /* dynamic configuation */ - switch (status) { - case SWITCH_STATUS_SUCCESS: - break; - case SWITCH_STATUS_NOOP: - switch_log_printf(SWITCH_CHANNEL_SESSION_LOG(session), SWITCH_LOG_ERROR, "Failed to set dynamic parameters for avmd session. Session is NULL!\n"); - goto end; - case SWITCH_STATUS_FALSE: - switch_log_printf(SWITCH_CHANNEL_SESSION_LOG(session), SWITCH_LOG_ERROR, "Failed to set dynamic parameters for avmd session. Parsing error, please check the parameters passed to this APP.\n"); - goto end; - default: - switch_log_printf(SWITCH_CHANNEL_SESSION_LOG(session), SWITCH_LOG_ERROR, "Failed to set dynamic parameteres for avmd session. Unknown error\n"); - goto end; - } + status = avmd_parse_cmd_data(avmd_session, data, AVMD_APP_START_APP); /* dynamic configuation */ + switch (status) { + case SWITCH_STATUS_SUCCESS: + break; + case SWITCH_STATUS_NOOP: + switch_log_printf(SWITCH_CHANNEL_SESSION_LOG(session), SWITCH_LOG_ERROR, "Failed to set dynamic parameters for avmd session. Session is NULL!\n"); + goto end; + case SWITCH_STATUS_FALSE: + switch_log_printf(SWITCH_CHANNEL_SESSION_LOG(session), SWITCH_LOG_ERROR, "Failed to set dynamic parameters for avmd session. Parsing error, please check the parameters passed to this APP.\n"); + goto end; + default: + switch_log_printf(SWITCH_CHANNEL_SESSION_LOG(session), SWITCH_LOG_ERROR, "Failed to set dynamic parameteres for avmd session. Unknown error\n"); + goto end; + } report = avmd_session->settings.report_status; - status = init_avmd_session_data(avmd_session, session, avmd_globals.mutex); - if (status != SWITCH_STATUS_SUCCESS) { - switch (status) { - case SWITCH_STATUS_MEMERR: - switch_log_printf(SWITCH_CHANNEL_SESSION_LOG(session), SWITCH_LOG_ERROR, "Failed to init avmd session. Buffer error!\n"); - break; - case SWITCH_STATUS_MORE_DATA: - switch_log_printf(SWITCH_CHANNEL_SESSION_LOG(session), SWITCH_LOG_ERROR, "Failed to init avmd session. SMA buffer size is 0!\n"); - break; - case SWITCH_STATUS_FALSE: - switch_log_printf(SWITCH_CHANNEL_SESSION_LOG(session), SWITCH_LOG_ERROR, "Failed to init avmd session. SMA buffers error\n"); - break; - default: - switch_log_printf(SWITCH_CHANNEL_SESSION_LOG(session), SWITCH_LOG_ERROR, "Failed to init avmd session. Unknown error\n"); - break; - } - goto end; - } + status = init_avmd_session_data(avmd_session, session, avmd_globals.mutex); + if (status != SWITCH_STATUS_SUCCESS) { + switch (status) { + case SWITCH_STATUS_MEMERR: + switch_log_printf(SWITCH_CHANNEL_SESSION_LOG(session), SWITCH_LOG_ERROR, "Failed to init avmd session. Buffer error!\n"); + break; + case SWITCH_STATUS_MORE_DATA: + switch_log_printf(SWITCH_CHANNEL_SESSION_LOG(session), SWITCH_LOG_ERROR, "Failed to init avmd session. SMA buffer size is 0!\n"); + break; + case SWITCH_STATUS_FALSE: + switch_log_printf(SWITCH_CHANNEL_SESSION_LOG(session), SWITCH_LOG_ERROR, "Failed to init avmd session. SMA buffers error\n"); + break; + default: + switch_log_printf(SWITCH_CHANNEL_SESSION_LOG(session), SWITCH_LOG_ERROR, "Failed to init avmd session. Unknown error\n"); + break; + } + goto end; + } - switch_mutex_lock(avmd_session->mutex); - if (avmd_session->settings.report_status == 1) { /* dump dynamic parameters */ - avmd_config_dump(avmd_session); - } - if ((SWITCH_CALL_DIRECTION_OUTBOUND == switch_channel_direction(channel)) && (avmd_session->settings.outbound_channnel == 1)) { - flags |= SMBF_READ_REPLACE; + switch_mutex_lock(avmd_session->mutex); + if (avmd_session->settings.report_status == 1) { /* dump dynamic parameters */ + avmd_config_dump(avmd_session); + } + if ((SWITCH_CALL_DIRECTION_OUTBOUND == switch_channel_direction(channel)) && (avmd_session->settings.outbound_channnel == 1)) { + flags |= SMBF_READ_REPLACE; direction = "READ_REPLACE"; - } - if ((SWITCH_CALL_DIRECTION_INBOUND == switch_channel_direction(channel)) && (avmd_session->settings.inbound_channnel == 1)) { - flags |= SMBF_WRITE_REPLACE; + } + if ((SWITCH_CALL_DIRECTION_INBOUND == switch_channel_direction(channel)) && (avmd_session->settings.inbound_channnel == 1)) { + flags |= SMBF_WRITE_REPLACE; if (!strcmp(direction, "READ_REPLACE")) { direction = "READ_REPLACE | WRITE_REPLACE"; } else { direction = "WRITE_REPLACE"; } - } + } - if (flags == 0) { - switch_log_printf(SWITCH_CHANNEL_SESSION_LOG(session), SWITCH_LOG_ERROR, "Can't set direction for channel [%s]\n", switch_channel_get_name(channel)); - status = SWITCH_STATUS_FALSE; - goto end_unlock; - } + if (flags == 0) { + switch_log_printf(SWITCH_CHANNEL_SESSION_LOG(session), SWITCH_LOG_ERROR, "Can't set direction for channel [%s]\n", switch_channel_get_name(channel)); + status = SWITCH_STATUS_FALSE; + goto end_unlock; + } - if ((SWITCH_CALL_DIRECTION_OUTBOUND == switch_channel_direction(channel)) && (avmd_session->settings.outbound_channnel == 1)) { - if (switch_channel_test_flag(channel, CF_MEDIA_SET) == 0) { - switch_log_printf(SWITCH_CHANNEL_SESSION_LOG(session), SWITCH_LOG_ERROR, "Channel [%s] has no codec assigned yet. Please try again\n", switch_channel_get_name(channel)); - status = SWITCH_STATUS_FALSE; - goto end_unlock; - } - } + if ((SWITCH_CALL_DIRECTION_OUTBOUND == switch_channel_direction(channel)) && (avmd_session->settings.outbound_channnel == 1)) { + if (switch_channel_test_flag(channel, CF_MEDIA_SET) == 0) { + switch_log_printf(SWITCH_CHANNEL_SESSION_LOG(session), SWITCH_LOG_ERROR, "Channel [%s] has no codec assigned yet. Please try again\n", switch_channel_get_name(channel)); + status = SWITCH_STATUS_FALSE; + goto end_unlock; + } + } - status = avmd_launch_threads(avmd_session); - if (status != SWITCH_STATUS_SUCCESS) { - switch_log_printf(SWITCH_CHANNEL_SESSION_LOG(session), SWITCH_LOG_ERROR, "Failed to start detection threads\n"); - avmd_join_threads(avmd_session); - switch_log_printf(SWITCH_CHANNEL_SESSION_LOG(session), SWITCH_LOG_INFO, "Joined detection threads\n"); - goto end_unlock; - } + status = avmd_launch_threads(avmd_session); + if (status != SWITCH_STATUS_SUCCESS) { + switch_log_printf(SWITCH_CHANNEL_SESSION_LOG(session), SWITCH_LOG_ERROR, "Failed to start detection threads\n"); + avmd_join_threads(avmd_session); + switch_log_printf(SWITCH_CHANNEL_SESSION_LOG(session), SWITCH_LOG_INFO, "Joined detection threads\n"); + goto end_unlock; + } - status = switch_core_media_bug_add(session, "avmd", NULL, avmd_callback, avmd_session, 0, flags, &bug); /* Add a media bug that allows me to intercept the audio stream */ - if (status != SWITCH_STATUS_SUCCESS) { /* If adding a media bug fails exit */ - switch_log_printf(SWITCH_CHANNEL_SESSION_LOG(session), SWITCH_LOG_ERROR, "Failed to add media bug!\n"); + status = switch_core_media_bug_add(session, "avmd", NULL, avmd_callback, avmd_session, 0, flags, &bug); /* Add a media bug that allows me to intercept the audio stream */ + if (status != SWITCH_STATUS_SUCCESS) { /* If adding a media bug fails exit */ + switch_log_printf(SWITCH_CHANNEL_SESSION_LOG(session), SWITCH_LOG_ERROR, "Failed to add media bug!\n"); switch_mutex_unlock(avmd_session->mutex); avmd_session_close(avmd_session); - goto end; - } + goto end; + } - switch_mutex_lock(avmd_globals.mutex); - ++avmd_globals.session_n; - switch_mutex_unlock(avmd_globals.mutex); + switch_mutex_lock(avmd_globals.mutex); + ++avmd_globals.session_n; + switch_mutex_unlock(avmd_globals.mutex); - switch_channel_set_private(channel, "_avmd_", bug); /* Set the avmd tag to detect an existing avmd media bug */ - avmd_fire_event(AVMD_EVENT_SESSION_START, session, 0, 0, 0, 0, 0, 0, 0, 0, avmd_session->start_time, 0, 0, 0, 0); - if (avmd_session->settings.report_status == 1) { - switch_log_printf(SWITCH_CHANNEL_SESSION_LOG(session), SWITCH_LOG_INFO, "Avmd on channel [%s] started! direction=%s\n", switch_channel_get_name(channel), direction); - } + switch_channel_set_private(channel, "_avmd_", bug); /* Set the avmd tag to detect an existing avmd media bug */ + avmd_fire_event(AVMD_EVENT_SESSION_START, session, 0, 0, 0, 0, 0, 0, 0, 0, avmd_session->start_time, 0, 0, 0, 0); + if (avmd_session->settings.report_status == 1) { + switch_log_printf(SWITCH_CHANNEL_SESSION_LOG(session), SWITCH_LOG_INFO, "Avmd on channel [%s] started! direction=%s\n", switch_channel_get_name(channel), direction); + } end_unlock: - switch_mutex_unlock(avmd_session->mutex); + switch_mutex_unlock(avmd_session->mutex); end: - if (status != SWITCH_STATUS_SUCCESS) { - if (avmd_session == NULL || report) { - switch_log_printf(SWITCH_CHANNEL_SESSION_LOG(session), SWITCH_LOG_ERROR, "Avmd on channel [%s] NOT started\n", switch_channel_get_name(channel)); - } - } - return; + if (status != SWITCH_STATUS_SUCCESS) { + if (avmd_session == NULL || report) { + switch_log_printf(SWITCH_CHANNEL_SESSION_LOG(session), SWITCH_LOG_ERROR, "Avmd on channel [%s] NOT started\n", switch_channel_get_name(channel)); + } + } + return; } SWITCH_STANDARD_APP(avmd_stop_app) { - switch_media_bug_t *bug; - switch_channel_t *channel; - avmd_session_t *avmd_session; - switch_time_t start_time, stop_time, total_time; - uint8_t report_status = 0; - avmd_beep_state_t beep_status = BEEP_NOTDETECTED; + switch_media_bug_t *bug; + switch_channel_t *channel; + avmd_session_t *avmd_session; + switch_time_t start_time, stop_time, total_time; + uint8_t report_status = 0; + avmd_beep_state_t beep_status = BEEP_NOTDETECTED; - if (session == NULL) { - switch_log_printf(SWITCH_CHANNEL_SESSION_LOG(session), SWITCH_LOG_ERROR, "FreeSWITCH is NULL! Please report to developers\n"); - return; - } + if (session == NULL) { + switch_log_printf(SWITCH_CHANNEL_SESSION_LOG(session), SWITCH_LOG_ERROR, "FreeSWITCH is NULL! Please report to developers\n"); + return; + } - /* Get current channel of the session to tag the session. This indicates that our module is present - * At this moment this cannot return NULL, it will either succeed or assert failed, but we make ourself secure anyway */ - channel = switch_core_session_get_channel(session); - if (channel == NULL) { - switch_log_printf(SWITCH_CHANNEL_SESSION_LOG(session), SWITCH_LOG_ERROR, "No channel for FreeSWITCH session! Please report this to the developers.\n"); - return; - } + /* Get current channel of the session to tag the session. This indicates that our module is present + * At this moment this cannot return NULL, it will either succeed or assert failed, but we make ourself secure anyway */ + channel = switch_core_session_get_channel(session); + if (channel == NULL) { + switch_log_printf(SWITCH_CHANNEL_SESSION_LOG(session), SWITCH_LOG_ERROR, "No channel for FreeSWITCH session! Please report this to the developers.\n"); + return; + } - bug = (switch_media_bug_t *) switch_channel_get_private(channel, "_avmd_"); - if (bug == NULL) { - switch_log_printf(SWITCH_CHANNEL_SESSION_LOG(session), SWITCH_LOG_ERROR, "Stop failed - no avmd session running on this channel [%s]!\n", switch_channel_get_name(channel)); - return; - } + bug = (switch_media_bug_t *) switch_channel_get_private(channel, "_avmd_"); + if (bug == NULL) { + switch_log_printf(SWITCH_CHANNEL_SESSION_LOG(session), SWITCH_LOG_ERROR, "Stop failed - no avmd session running on this channel [%s]!\n", switch_channel_get_name(channel)); + return; + } - avmd_session = switch_core_media_bug_get_user_data(bug); - if (avmd_session == NULL) { - switch_log_printf(SWITCH_CHANNEL_SESSION_LOG(session), SWITCH_LOG_ERROR, "Stop failed - no avmd session object, stop event not fired on this channel [%s]!\n", switch_channel_get_name(channel)); - } else { - switch_mutex_lock(avmd_session->mutex); - report_status = avmd_session->settings.report_status; - beep_status = avmd_session->state.beep_state; - avmd_session->stop_time = switch_micro_time_now(); - start_time = avmd_session->start_time; - stop_time = avmd_session->stop_time; - total_time = stop_time - start_time; - switch_mutex_unlock(avmd_session->mutex); - avmd_fire_event(AVMD_EVENT_SESSION_STOP, session, 0, 0, 0, 0, beep_status, 1, 0, 0, start_time, stop_time, 0, 0, 0); - if (report_status == 1) { - switch_log_printf(SWITCH_CHANNEL_SESSION_LOG(session), SWITCH_LOG_INFO, "Avmd on channel [%s] stopped, beep status: [%s], total running time [%" PRId64 "] [us]\n", switch_channel_get_name(channel), beep_status == BEEP_DETECTED ? "DETECTED" : "NOTDETECTED", total_time); - } - } - switch_channel_set_private(channel, "_avmd_", NULL); - switch_core_media_bug_remove(session, &bug); + avmd_session = switch_core_media_bug_get_user_data(bug); + if (avmd_session == NULL) { + switch_log_printf(SWITCH_CHANNEL_SESSION_LOG(session), SWITCH_LOG_ERROR, "Stop failed - no avmd session object, stop event not fired on this channel [%s]!\n", switch_channel_get_name(channel)); + } else { + switch_mutex_lock(avmd_session->mutex); + report_status = avmd_session->settings.report_status; + beep_status = avmd_session->state.beep_state; + avmd_session->stop_time = switch_micro_time_now(); + start_time = avmd_session->start_time; + stop_time = avmd_session->stop_time; + total_time = stop_time - start_time; + switch_mutex_unlock(avmd_session->mutex); + avmd_fire_event(AVMD_EVENT_SESSION_STOP, session, 0, 0, 0, 0, beep_status, 1, 0, 0, start_time, stop_time, 0, 0, 0); + if (report_status == 1) { + switch_log_printf(SWITCH_CHANNEL_SESSION_LOG(session), SWITCH_LOG_INFO, "Avmd on channel [%s] stopped, beep status: [%s], total running time [%" PRId64 "] [us]\n", switch_channel_get_name(channel), beep_status == BEEP_DETECTED ? "DETECTED" : "NOTDETECTED", total_time); + } + } + switch_channel_set_private(channel, "_avmd_", NULL); + switch_core_media_bug_remove(session, &bug); - return; + return; } /*! \brief FreeSWITCH application handler function. * This handles calls made from applications such as LUA and the dialplan. */ SWITCH_STANDARD_APP(avmd_start_function) { - switch_media_bug_t *bug; - switch_channel_t *channel; + switch_media_bug_t *bug; + switch_channel_t *channel; - switch_log_printf(SWITCH_CHANNEL_LOG, SWITCH_LOG_WARNING, "YOU ARE USING DEPRECATED APP INTERFACE. Please read documentation about new syntax\n"); - if (session == NULL) { - switch_log_printf(SWITCH_CHANNEL_LOG, SWITCH_LOG_ERROR, "No FreeSWITCH session assigned!\n"); - return; - } + switch_log_printf(SWITCH_CHANNEL_LOG, SWITCH_LOG_WARNING, "YOU ARE USING DEPRECATED APP INTERFACE. Please read documentation about new syntax\n"); + if (session == NULL) { + switch_log_printf(SWITCH_CHANNEL_LOG, SWITCH_LOG_ERROR, "No FreeSWITCH session assigned!\n"); + return; + } - channel = switch_core_session_get_channel(session); + channel = switch_core_session_get_channel(session); - bug = (switch_media_bug_t *) switch_channel_get_private(channel, "_avmd_"); - if (bug != NULL) { - if (strcasecmp(data, "stop") == 0) { - switch_channel_set_private(channel, "_avmd_", NULL); - switch_core_media_bug_remove(session, &bug); - return; - } - switch_log_printf(SWITCH_CHANNEL_SESSION_LOG(session), SWITCH_LOG_WARNING, "Cannot run 2 at once on the same channel!\n"); - return; - } - avmd_start_app(session, NULL); + bug = (switch_media_bug_t *) switch_channel_get_private(channel, "_avmd_"); + if (bug != NULL) { + if (strcasecmp(data, "stop") == 0) { + switch_channel_set_private(channel, "_avmd_", NULL); + switch_core_media_bug_remove(session, &bug); + return; + } + switch_log_printf(SWITCH_CHANNEL_SESSION_LOG(session), SWITCH_LOG_WARNING, "Cannot run 2 at once on the same channel!\n"); + return; + } + avmd_start_app(session, NULL); } SWITCH_MODULE_SHUTDOWN_FUNCTION(mod_avmd_shutdown) { - size_t session_n; + size_t session_n; #ifndef WIN32 - int res; + int res; #endif - switch_mutex_lock(avmd_globals.mutex); + switch_mutex_lock(avmd_globals.mutex); - session_n = avmd_globals.session_n; - if (session_n > 0) { - switch_mutex_unlock(avmd_globals.mutex); - switch_log_printf(SWITCH_CHANNEL_LOG, SWITCH_LOG_ERROR, "PLEASE DO NOT RELOAD MODULE WHILE SESSIONS ARE RUNNING\n"); - } + session_n = avmd_globals.session_n; + if (session_n > 0) { + switch_mutex_unlock(avmd_globals.mutex); + switch_log_printf(SWITCH_CHANNEL_LOG, SWITCH_LOG_ERROR, "PLEASE DO NOT RELOAD MODULE WHILE SESSIONS ARE RUNNING\n"); + } - avmd_unregister_all_events(); + avmd_unregister_all_events(); #ifndef WIN32 - if (avmd_globals.settings.fast_math == 1) { - res = destroy_fast_acosf(); - if (res != 0) { - switch (res) { - case -1: - switch_log_printf(SWITCH_CHANNEL_LOG, SWITCH_LOG_ERROR, "Failed unmap arc cosine table\n"); - break; - case -2: - switch_log_printf(SWITCH_CHANNEL_LOG, SWITCH_LOG_ERROR, "Failed closing arc cosine table\n"); - break; - default: - break; - } - } - } + if (avmd_globals.settings.fast_math == 1) { + res = destroy_fast_acosf(); + if (res != 0) { + switch (res) { + case -1: + switch_log_printf(SWITCH_CHANNEL_LOG, SWITCH_LOG_ERROR, "Failed unmap arc cosine table\n"); + break; + case -2: + switch_log_printf(SWITCH_CHANNEL_LOG, SWITCH_LOG_ERROR, "Failed closing arc cosine table\n"); + break; + default: + break; + } + } + } #endif - switch_event_unbind_callback(avmd_reloadxml_event_handler); - switch_mutex_unlock(avmd_globals.mutex); - switch_mutex_destroy(avmd_globals.mutex); - switch_log_printf(SWITCH_CHANNEL_LOG, SWITCH_LOG_NOTICE, "Advanced voicemail detection disabled\n"); - return SWITCH_STATUS_SUCCESS; + switch_event_unbind_callback(avmd_reloadxml_event_handler); + switch_mutex_unlock(avmd_globals.mutex); + switch_mutex_destroy(avmd_globals.mutex); + switch_log_printf(SWITCH_CHANNEL_LOG, SWITCH_LOG_NOTICE, "Advanced voicemail detection disabled\n"); + return SWITCH_STATUS_SUCCESS; } /*! \brief FreeSWITCH API handler function. */ SWITCH_STANDARD_API(avmd_api_main) { - switch_media_bug_t *bug = NULL; - avmd_session_t *avmd_session = NULL; - switch_channel_t *channel = NULL; - int argc; - const char *uuid = NULL, *uuid_dup = NULL; - const char *command = NULL; - char *dupped = NULL, *argv[AVMD_PARAMS_API_MAX + 1] = { 0 }; - switch_core_media_flag_t flags = 0; - switch_status_t status = SWITCH_STATUS_SUCCESS; - switch_core_session_t *fs_session = NULL; + switch_media_bug_t *bug = NULL; + avmd_session_t *avmd_session = NULL; + switch_channel_t *channel = NULL; + int argc; + const char *uuid = NULL, *uuid_dup = NULL; + const char *command = NULL; + char *dupped = NULL, *argv[AVMD_PARAMS_API_MAX + 1] = { 0 }; + switch_core_media_flag_t flags = 0; + switch_status_t status = SWITCH_STATUS_SUCCESS; + switch_core_session_t *fs_session = NULL; - switch_mutex_lock(avmd_globals.mutex); + switch_mutex_lock(avmd_globals.mutex); - if (zstr(cmd)) { - stream->write_function(stream, "-ERR, bad command!\n-USAGE: %s\n\n", AVMD_SYNTAX); - goto end; - } + if (zstr(cmd)) { + stream->write_function(stream, "-ERR, bad command!\n-USAGE: %s\n\n", AVMD_SYNTAX); + goto end; + } - dupped = strdup(cmd); - switch_assert(dupped); - argc = switch_separate_string((char*)dupped, ' ', argv, (sizeof(argv) / sizeof(argv[0]))); + dupped = strdup(cmd); + switch_assert(dupped); + argc = switch_separate_string((char*)dupped, ' ', argv, (sizeof(argv) / sizeof(argv[0]))); - if (argc < AVMD_PARAMS_API_MIN) { - stream->write_function(stream, "-ERR, avmd takes [%u] min and [%u] max parameters!\n-USAGE: %s\n\n", AVMD_PARAMS_API_MIN, AVMD_PARAMS_API_MAX, AVMD_SYNTAX); - goto end; - } + if (argc < AVMD_PARAMS_API_MIN) { + stream->write_function(stream, "-ERR, avmd takes [%u] min and [%u] max parameters!\n-USAGE: %s\n\n", AVMD_PARAMS_API_MIN, AVMD_PARAMS_API_MAX, AVMD_SYNTAX); + goto end; + } - command = argv[0]; - if (strcasecmp(command, "reload") == 0) { - status = avmd_load_xml_configuration(NULL); - if (avmd_globals.settings.report_status == 1) { - if (status != SWITCH_STATUS_SUCCESS) { - stream->write_function(stream, "-ERR, couldn't reload XML configuration\n"); - switch_log_printf(SWITCH_CHANNEL_LOG, SWITCH_LOG_ERROR, "Couldn't reload XML configuration\n"); - } else { - stream->write_function(stream, "+OK\n XML reloaded\n\n"); - switch_log_printf(SWITCH_CHANNEL_LOG, SWITCH_LOG_INFO, "XML reloaded\n"); - } - goto end; - } - } - if (strcasecmp(command, "load") == 0) { - if (argc != 2) { - stream->write_function(stream, "-ERR, load command takes 1 parameter!\n-USAGE: %s\n\n", AVMD_SYNTAX); - goto end; - } - command = argv[1]; - if (strcasecmp(command, "inbound") == 0) { - status = avmd_load_xml_inbound_configuration(NULL); - if (avmd_globals.settings.report_status == 1) { - if (status != SWITCH_STATUS_SUCCESS) { - stream->write_function(stream, "-ERR, couldn't load XML configuration\n"); - switch_log_printf(SWITCH_CHANNEL_LOG, SWITCH_LOG_ERROR, "Couldn't load XML configuration\n"); - } else { - stream->write_function(stream, "+OK\n inbound XML configuration loaded\n\n"); - switch_log_printf(SWITCH_CHANNEL_LOG, SWITCH_LOG_INFO, "Inbound XML configuration loaded\n"); - } - goto end; - } - } else if (strcasecmp(command, "outbound") == 0) { - status = avmd_load_xml_outbound_configuration(NULL); - if (avmd_globals.settings.report_status == 1) { - if (status != SWITCH_STATUS_SUCCESS) { - stream->write_function(stream, "-ERR, couldn't load XML configuration\n"); - switch_log_printf(SWITCH_CHANNEL_LOG, SWITCH_LOG_ERROR, "Couldn't load XML configuration\n"); - } else { - stream->write_function(stream, "+OK\n outbound XML configuration loaded\n\n"); - switch_log_printf(SWITCH_CHANNEL_LOG, SWITCH_LOG_INFO, "Outbound XML configuration loaded\n"); - } - goto end; - } - } else { - stream->write_function(stream, "-ERR, load command: bad syntax!\n-USAGE: %s\n\n", AVMD_SYNTAX); - } - goto end; - } - if (strcasecmp(command, "set") == 0) { - if (argc != 2) { - stream->write_function(stream, "-ERR, set command takes 1 parameter!\n-USAGE: %s\n\n", AVMD_SYNTAX); - goto end; - } - command = argv[1]; - if (strcasecmp(command, "inbound") == 0) { - avmd_set_xml_inbound_configuration(NULL); - if (avmd_globals.settings.report_status == 1) { - stream->write_function(stream, "+OK\n inbound XML configuration loaded\n\n"); - switch_log_printf(SWITCH_CHANNEL_LOG, SWITCH_LOG_INFO, "Inbound XML configuration loaded\n"); - } - } else if (strcasecmp(command, "outbound") == 0) { - avmd_set_xml_outbound_configuration(NULL); - if (avmd_globals.settings.report_status == 1) { - stream->write_function(stream, "+OK\n outbound XML configuration loaded\n\n"); - switch_log_printf(SWITCH_CHANNEL_LOG, SWITCH_LOG_INFO, "Outbound XML configuration loaded\n"); - } - } else if (strcasecmp(command, "default") == 0) { - avmd_set_xml_default_configuration(NULL); - if (avmd_globals.settings.report_status == 1) { - stream->write_function(stream, "+OK\n reset to factory settings\n\n"); - switch_log_printf(SWITCH_CHANNEL_LOG, SWITCH_LOG_INFO, "Reset to factory settings\n"); - } - } else { - stream->write_function(stream, "-ERR, set command: bad syntax!\n-USAGE: %s\n\n", AVMD_SYNTAX); - } - goto end; - } - if (strcasecmp(command, "show") == 0) { - avmd_show(stream, NULL); - if (avmd_globals.settings.report_status == 1) { - stream->write_function(stream, "+OK\n show\n\n"); - } - goto end; - } + command = argv[0]; + if (strcasecmp(command, "reload") == 0) { + status = avmd_load_xml_configuration(NULL); + if (avmd_globals.settings.report_status == 1) { + if (status != SWITCH_STATUS_SUCCESS) { + stream->write_function(stream, "-ERR, couldn't reload XML configuration\n"); + switch_log_printf(SWITCH_CHANNEL_LOG, SWITCH_LOG_ERROR, "Couldn't reload XML configuration\n"); + } else { + stream->write_function(stream, "+OK\n XML reloaded\n\n"); + switch_log_printf(SWITCH_CHANNEL_LOG, SWITCH_LOG_INFO, "XML reloaded\n"); + } + goto end; + } + } + if (strcasecmp(command, "load") == 0) { + if (argc != 2) { + stream->write_function(stream, "-ERR, load command takes 1 parameter!\n-USAGE: %s\n\n", AVMD_SYNTAX); + goto end; + } + command = argv[1]; + if (strcasecmp(command, "inbound") == 0) { + status = avmd_load_xml_inbound_configuration(NULL); + if (avmd_globals.settings.report_status == 1) { + if (status != SWITCH_STATUS_SUCCESS) { + stream->write_function(stream, "-ERR, couldn't load XML configuration\n"); + switch_log_printf(SWITCH_CHANNEL_LOG, SWITCH_LOG_ERROR, "Couldn't load XML configuration\n"); + } else { + stream->write_function(stream, "+OK\n inbound XML configuration loaded\n\n"); + switch_log_printf(SWITCH_CHANNEL_LOG, SWITCH_LOG_INFO, "Inbound XML configuration loaded\n"); + } + goto end; + } + } else if (strcasecmp(command, "outbound") == 0) { + status = avmd_load_xml_outbound_configuration(NULL); + if (avmd_globals.settings.report_status == 1) { + if (status != SWITCH_STATUS_SUCCESS) { + stream->write_function(stream, "-ERR, couldn't load XML configuration\n"); + switch_log_printf(SWITCH_CHANNEL_LOG, SWITCH_LOG_ERROR, "Couldn't load XML configuration\n"); + } else { + stream->write_function(stream, "+OK\n outbound XML configuration loaded\n\n"); + switch_log_printf(SWITCH_CHANNEL_LOG, SWITCH_LOG_INFO, "Outbound XML configuration loaded\n"); + } + goto end; + } + } else { + stream->write_function(stream, "-ERR, load command: bad syntax!\n-USAGE: %s\n\n", AVMD_SYNTAX); + } + goto end; + } + if (strcasecmp(command, "set") == 0) { + if (argc != 2) { + stream->write_function(stream, "-ERR, set command takes 1 parameter!\n-USAGE: %s\n\n", AVMD_SYNTAX); + goto end; + } + command = argv[1]; + if (strcasecmp(command, "inbound") == 0) { + avmd_set_xml_inbound_configuration(NULL); + if (avmd_globals.settings.report_status == 1) { + stream->write_function(stream, "+OK\n inbound XML configuration loaded\n\n"); + switch_log_printf(SWITCH_CHANNEL_LOG, SWITCH_LOG_INFO, "Inbound XML configuration loaded\n"); + } + } else if (strcasecmp(command, "outbound") == 0) { + avmd_set_xml_outbound_configuration(NULL); + if (avmd_globals.settings.report_status == 1) { + stream->write_function(stream, "+OK\n outbound XML configuration loaded\n\n"); + switch_log_printf(SWITCH_CHANNEL_LOG, SWITCH_LOG_INFO, "Outbound XML configuration loaded\n"); + } + } else if (strcasecmp(command, "default") == 0) { + avmd_set_xml_default_configuration(NULL); + if (avmd_globals.settings.report_status == 1) { + stream->write_function(stream, "+OK\n reset to factory settings\n\n"); + switch_log_printf(SWITCH_CHANNEL_LOG, SWITCH_LOG_INFO, "Reset to factory settings\n"); + } + } else { + stream->write_function(stream, "-ERR, set command: bad syntax!\n-USAGE: %s\n\n", AVMD_SYNTAX); + } + goto end; + } + if (strcasecmp(command, "show") == 0) { + avmd_show(stream, NULL); + if (avmd_globals.settings.report_status == 1) { + stream->write_function(stream, "+OK\n show\n\n"); + } + goto end; + } - uuid = argv[0]; - command = argv[1]; + uuid = argv[0]; + command = argv[1]; - fs_session = switch_core_session_locate(uuid); /* using uuid locate a reference to the FreeSWITCH session */ - if (fs_session == NULL) { - stream->write_function(stream, "-ERR, no FreeSWITCH session for uuid [%s]!\n-USAGE: %s\n\n", uuid, AVMD_SYNTAX); - goto end; - } + fs_session = switch_core_session_locate(uuid); /* using uuid locate a reference to the FreeSWITCH session */ + if (fs_session == NULL) { + stream->write_function(stream, "-ERR, no FreeSWITCH session for uuid [%s]!\n-USAGE: %s\n\n", uuid, AVMD_SYNTAX); + goto end; + } - /* Get current channel of the session to tag the session. This indicates that our module is present - * At this moment this cannot return NULL, it will either succeed or assert failed, but we make ourself secure anyway */ - channel = switch_core_session_get_channel(fs_session); - if (channel == NULL) { - stream->write_function(stream, "-ERR, no channel for FreeSWITCH session [%s]!\n Please report this to the developers\n\n", uuid); - goto end; - } + /* Get current channel of the session to tag the session. This indicates that our module is present + * At this moment this cannot return NULL, it will either succeed or assert failed, but we make ourself secure anyway */ + channel = switch_core_session_get_channel(fs_session); + if (channel == NULL) { + stream->write_function(stream, "-ERR, no channel for FreeSWITCH session [%s]!\n Please report this to the developers\n\n", uuid); + goto end; + } - bug = (switch_media_bug_t *) switch_channel_get_private(channel, "_avmd_"); - if (bug != NULL) { - if (strcasecmp(command, "stop") == 0) { - avmd_session = (avmd_session_t*) switch_core_media_bug_get_user_data(bug); - if (avmd_session == NULL) { - switch_log_printf(SWITCH_CHANNEL_SESSION_LOG(fs_session), SWITCH_LOG_ERROR, "Stop failed - no avmd session object on this channel [%s]!\n", switch_channel_get_name(channel)); - goto end; - } - uuid_dup = switch_core_strdup(switch_core_session_get_pool(fs_session), uuid); - switch_channel_set_private(channel, "_avmd_", NULL); - switch_core_media_bug_remove(fs_session, &bug); - avmd_fire_event(AVMD_EVENT_SESSION_STOP, fs_session, 0, 0, 0, 0, 0, 0, 0, 0, avmd_session->start_time, avmd_session->stop_time, 0, 0, 0); - if (avmd_globals.settings.report_status == 1) { - stream->write_function(stream, "+OK\n [%s] [%s] stopped\n\n", uuid_dup, switch_channel_get_name(channel)); - switch_log_printf(SWITCH_CHANNEL_SESSION_LOG(fs_session), SWITCH_LOG_INFO, "Avmd on channel [%s] stopped!\n", switch_channel_get_name(channel)); - } - goto end; - } - if (avmd_globals.settings.report_status == 1) { - switch_log_printf(SWITCH_CHANNEL_SESSION_LOG(fs_session), SWITCH_LOG_ERROR, "Avmd already started!\n"); - stream->write_function(stream, "-ERR, avmd for FreeSWITCH session [%s]\n already started\n\n", uuid); - } - goto end; - } + bug = (switch_media_bug_t *) switch_channel_get_private(channel, "_avmd_"); + if (bug != NULL) { + if (strcasecmp(command, "stop") == 0) { + avmd_session = (avmd_session_t*) switch_core_media_bug_get_user_data(bug); + if (avmd_session == NULL) { + switch_log_printf(SWITCH_CHANNEL_SESSION_LOG(fs_session), SWITCH_LOG_ERROR, "Stop failed - no avmd session object on this channel [%s]!\n", switch_channel_get_name(channel)); + goto end; + } + uuid_dup = switch_core_strdup(switch_core_session_get_pool(fs_session), uuid); + switch_channel_set_private(channel, "_avmd_", NULL); + switch_core_media_bug_remove(fs_session, &bug); + avmd_fire_event(AVMD_EVENT_SESSION_STOP, fs_session, 0, 0, 0, 0, 0, 0, 0, 0, avmd_session->start_time, avmd_session->stop_time, 0, 0, 0); + if (avmd_globals.settings.report_status == 1) { + stream->write_function(stream, "+OK\n [%s] [%s] stopped\n\n", uuid_dup, switch_channel_get_name(channel)); + switch_log_printf(SWITCH_CHANNEL_SESSION_LOG(fs_session), SWITCH_LOG_INFO, "Avmd on channel [%s] stopped!\n", switch_channel_get_name(channel)); + } + goto end; + } + if (avmd_globals.settings.report_status == 1) { + switch_log_printf(SWITCH_CHANNEL_SESSION_LOG(fs_session), SWITCH_LOG_ERROR, "Avmd already started!\n"); + stream->write_function(stream, "-ERR, avmd for FreeSWITCH session [%s]\n already started\n\n", uuid); + } + goto end; + } - if (strcasecmp(command, "stop") == 0) { - uuid_dup = switch_core_strdup(switch_core_session_get_pool(fs_session), uuid); - stream->write_function(stream, "+ERR, avmd has not yet been started on\n [%s] [%s]\n\n", uuid_dup, switch_channel_get_name(channel)); - switch_log_printf(SWITCH_CHANNEL_SESSION_LOG(fs_session), SWITCH_LOG_ERROR, "Stop failed - avmd has not yet been started on channel [%s]!\n", switch_channel_get_name(channel)); - goto end; - } - if ((SWITCH_CALL_DIRECTION_OUTBOUND == switch_channel_direction(channel)) && (avmd_globals.settings.outbound_channnel == 1)) { - flags |= SMBF_READ_REPLACE; - } - if ((SWITCH_CALL_DIRECTION_INBOUND == switch_channel_direction(channel)) && (avmd_globals.settings.inbound_channnel == 1)) { - flags |= SMBF_WRITE_REPLACE; - } - if (flags == 0) { - stream->write_function(stream, "-ERR, can't set direction for channel [%s]\n for FreeSWITCH session [%s]. Please check avmd configuration\n\n", switch_channel_get_name(channel), uuid); - switch_log_printf(SWITCH_CHANNEL_SESSION_LOG(fs_session), SWITCH_LOG_ERROR, "Can't set direction for channel [%s]\n", switch_channel_get_name(channel)); - status = SWITCH_STATUS_FALSE; - goto end; - } - if ((SWITCH_CALL_DIRECTION_OUTBOUND == switch_channel_direction(channel)) && (avmd_globals.settings.outbound_channnel == 1)) { - if (switch_channel_test_flag(channel, CF_MEDIA_SET) == 0) { - stream->write_function(stream, "-ERR, channel [%s] for FreeSWITCH session [%s]\n has no read codec assigned yet. Please try again.\n\n", switch_channel_get_name(channel), uuid); - switch_log_printf(SWITCH_CHANNEL_SESSION_LOG(fs_session), SWITCH_LOG_ERROR, "Channel [%s] has no codec assigned yet. Please try again\n", switch_channel_get_name(channel)); - status = SWITCH_STATUS_FALSE; - goto end; - } - } - if (strcasecmp(command, "start") != 0) { /* If we don't see the expected start exit */ - stream->write_function(stream, "-ERR, did you mean\n api avmd %s start ?\n-USAGE: %s\n\n", uuid, AVMD_SYNTAX); - goto end; - } + if (strcasecmp(command, "stop") == 0) { + uuid_dup = switch_core_strdup(switch_core_session_get_pool(fs_session), uuid); + stream->write_function(stream, "+ERR, avmd has not yet been started on\n [%s] [%s]\n\n", uuid_dup, switch_channel_get_name(channel)); + switch_log_printf(SWITCH_CHANNEL_SESSION_LOG(fs_session), SWITCH_LOG_ERROR, "Stop failed - avmd has not yet been started on channel [%s]!\n", switch_channel_get_name(channel)); + goto end; + } + if ((SWITCH_CALL_DIRECTION_OUTBOUND == switch_channel_direction(channel)) && (avmd_globals.settings.outbound_channnel == 1)) { + flags |= SMBF_READ_REPLACE; + } + if ((SWITCH_CALL_DIRECTION_INBOUND == switch_channel_direction(channel)) && (avmd_globals.settings.inbound_channnel == 1)) { + flags |= SMBF_WRITE_REPLACE; + } + if (flags == 0) { + stream->write_function(stream, "-ERR, can't set direction for channel [%s]\n for FreeSWITCH session [%s]. Please check avmd configuration\n\n", switch_channel_get_name(channel), uuid); + switch_log_printf(SWITCH_CHANNEL_SESSION_LOG(fs_session), SWITCH_LOG_ERROR, "Can't set direction for channel [%s]\n", switch_channel_get_name(channel)); + status = SWITCH_STATUS_FALSE; + goto end; + } + if ((SWITCH_CALL_DIRECTION_OUTBOUND == switch_channel_direction(channel)) && (avmd_globals.settings.outbound_channnel == 1)) { + if (switch_channel_test_flag(channel, CF_MEDIA_SET) == 0) { + stream->write_function(stream, "-ERR, channel [%s] for FreeSWITCH session [%s]\n has no read codec assigned yet. Please try again.\n\n", switch_channel_get_name(channel), uuid); + switch_log_printf(SWITCH_CHANNEL_SESSION_LOG(fs_session), SWITCH_LOG_ERROR, "Channel [%s] has no codec assigned yet. Please try again\n", switch_channel_get_name(channel)); + status = SWITCH_STATUS_FALSE; + goto end; + } + } + if (strcasecmp(command, "start") != 0) { /* If we don't see the expected start exit */ + stream->write_function(stream, "-ERR, did you mean\n api avmd %s start ?\n-USAGE: %s\n\n", uuid, AVMD_SYNTAX); + goto end; + } - avmd_session = (avmd_session_t *) switch_core_session_alloc(fs_session, sizeof(avmd_session_t)); /* Allocate memory attached to this FreeSWITCH session for use in the callback routine and to store state information */ - status = init_avmd_session_data(avmd_session, fs_session, NULL); - if (status != SWITCH_STATUS_SUCCESS) { - stream->write_function(stream, "-ERR, failed to initialize avmd session\n for FreeSWITCH session [%s]\n", uuid); - switch (status) { - case SWITCH_STATUS_MEMERR: - stream->write_function(stream, "-ERR, buffer error\n\n"); - switch_log_printf(SWITCH_CHANNEL_SESSION_LOG(fs_session), SWITCH_LOG_ERROR, "Failed to init avmd session. Buffer error!\n"); - break; - case SWITCH_STATUS_MORE_DATA: - stream->write_function(stream, "-ERR, SMA buffer size is 0\n\n"); - switch_log_printf(SWITCH_CHANNEL_SESSION_LOG(fs_session), SWITCH_LOG_ERROR, "Failed to init avmd session. SMA buffer size is 0!\n"); - break; - case SWITCH_STATUS_FALSE: - stream->write_function(stream, "-ERR, SMA buffer error\n\n"); - switch_log_printf(SWITCH_CHANNEL_SESSION_LOG(fs_session), SWITCH_LOG_ERROR, "Failed to init avmd session. SMA buffers error\n"); - break; - default: - stream->write_function(stream, "-ERR, unknown error\n\n"); - switch_log_printf(SWITCH_CHANNEL_SESSION_LOG(fs_session), SWITCH_LOG_ERROR, "Failed to init avmd session. Unknown error\n"); - break; - } - goto end; - } + avmd_session = (avmd_session_t *) switch_core_session_alloc(fs_session, sizeof(avmd_session_t)); /* Allocate memory attached to this FreeSWITCH session for use in the callback routine and to store state information */ + status = init_avmd_session_data(avmd_session, fs_session, NULL); + if (status != SWITCH_STATUS_SUCCESS) { + stream->write_function(stream, "-ERR, failed to initialize avmd session\n for FreeSWITCH session [%s]\n", uuid); + switch (status) { + case SWITCH_STATUS_MEMERR: + stream->write_function(stream, "-ERR, buffer error\n\n"); + switch_log_printf(SWITCH_CHANNEL_SESSION_LOG(fs_session), SWITCH_LOG_ERROR, "Failed to init avmd session. Buffer error!\n"); + break; + case SWITCH_STATUS_MORE_DATA: + stream->write_function(stream, "-ERR, SMA buffer size is 0\n\n"); + switch_log_printf(SWITCH_CHANNEL_SESSION_LOG(fs_session), SWITCH_LOG_ERROR, "Failed to init avmd session. SMA buffer size is 0!\n"); + break; + case SWITCH_STATUS_FALSE: + stream->write_function(stream, "-ERR, SMA buffer error\n\n"); + switch_log_printf(SWITCH_CHANNEL_SESSION_LOG(fs_session), SWITCH_LOG_ERROR, "Failed to init avmd session. SMA buffers error\n"); + break; + default: + stream->write_function(stream, "-ERR, unknown error\n\n"); + switch_log_printf(SWITCH_CHANNEL_SESSION_LOG(fs_session), SWITCH_LOG_ERROR, "Failed to init avmd session. Unknown error\n"); + break; + } + goto end; + } - status = switch_core_media_bug_add(fs_session, "avmd", NULL, avmd_callback, avmd_session, 0, flags, &bug); /* Add a media bug that allows me to intercept the reading leg of the audio stream */ + status = switch_core_media_bug_add(fs_session, "avmd", NULL, avmd_callback, avmd_session, 0, flags, &bug); /* Add a media bug that allows me to intercept the reading leg of the audio stream */ - if (status != SWITCH_STATUS_SUCCESS) { /* If adding a media bug fails exit */ - switch_log_printf(SWITCH_CHANNEL_SESSION_LOG(fs_session), SWITCH_LOG_ERROR, "Failed to add media bug!\n"); - stream->write_function(stream, "-ERR, [%s] failed to add media bug!\n\n", uuid); - goto end; - } + if (status != SWITCH_STATUS_SUCCESS) { /* If adding a media bug fails exit */ + switch_log_printf(SWITCH_CHANNEL_SESSION_LOG(fs_session), SWITCH_LOG_ERROR, "Failed to add media bug!\n"); + stream->write_function(stream, "-ERR, [%s] failed to add media bug!\n\n", uuid); + goto end; + } - switch_channel_set_private(channel, "_avmd_", bug); /* Set the vmd tag to detect an existing vmd media bug */ + switch_channel_set_private(channel, "_avmd_", bug); /* Set the vmd tag to detect an existing vmd media bug */ - avmd_fire_event(AVMD_EVENT_SESSION_START, fs_session, 0, 0, 0, 0, 0, 0, 0, 0, avmd_session->start_time, 0, 0, 0, 0); - if (avmd_globals.settings.report_status == 1) { - stream->write_function(stream, "+OK\n [%s] [%s] started!\n\n", uuid, switch_channel_get_name(channel)); - switch_log_printf(SWITCH_CHANNEL_SESSION_LOG(fs_session), SWITCH_LOG_INFO, "Avmd on channel [%s] started!\n", switch_channel_get_name(channel)); - switch_assert(status == SWITCH_STATUS_SUCCESS); - } + avmd_fire_event(AVMD_EVENT_SESSION_START, fs_session, 0, 0, 0, 0, 0, 0, 0, 0, avmd_session->start_time, 0, 0, 0, 0); + if (avmd_globals.settings.report_status == 1) { + stream->write_function(stream, "+OK\n [%s] [%s] started!\n\n", uuid, switch_channel_get_name(channel)); + switch_log_printf(SWITCH_CHANNEL_SESSION_LOG(fs_session), SWITCH_LOG_INFO, "Avmd on channel [%s] started!\n", switch_channel_get_name(channel)); + switch_assert(status == SWITCH_STATUS_SUCCESS); + } end: - if (status != SWITCH_STATUS_SUCCESS) { - switch_log_printf(SWITCH_CHANNEL_SESSION_LOG(fs_session), SWITCH_LOG_INFO, "AVMD session NOT started\n"); - if (avmd_globals.settings.report_status == 1) { - if ((uuid != NULL) && (channel != NULL)) { - stream->write_function(stream, "+ERR\n [%s] [%s] NOT started!\n\n", uuid, switch_channel_get_name(channel)); - } else { - stream->write_function(stream, "+ERR\n AVMD session NOT started!\n\n", switch_channel_get_name(channel)); - } - } - } - if (fs_session) { - switch_core_session_rwunlock(fs_session); - } + if (status != SWITCH_STATUS_SUCCESS) { + switch_log_printf(SWITCH_CHANNEL_SESSION_LOG(fs_session), SWITCH_LOG_INFO, "AVMD session NOT started\n"); + if (avmd_globals.settings.report_status == 1) { + if ((uuid != NULL) && (channel != NULL)) { + stream->write_function(stream, "+ERR\n [%s] [%s] NOT started!\n\n", uuid, switch_channel_get_name(channel)); + } else { + stream->write_function(stream, "+ERR\n AVMD session NOT started!\n\n", switch_channel_get_name(channel)); + } + } + } + if (fs_session) { + switch_core_session_rwunlock(fs_session); + } - switch_safe_free(dupped); + switch_safe_free(dupped); - switch_mutex_unlock(avmd_globals.mutex); + switch_mutex_unlock(avmd_globals.mutex); - return SWITCH_STATUS_SUCCESS; + return SWITCH_STATUS_SUCCESS; } static int avmd_decision_amplitude(const avmd_session_t *s, const struct avmd_buffer *b, double v, double rsd_threshold) { - double a, rsd; - size_t lpos; + double a, rsd; + size_t lpos; - lpos = b->sma_b.lpos; - if ((lpos >= AVMD_BEEP_LEN(s->rate) / b->resolution) && ((s->settings.require_continuous_streak_amp == 1 && (b->sma_amp_b.lpos > s->settings.sample_n_continuous_streak_amp) && (b->samples_streak_amp == 0)) - || (s->settings.require_continuous_streak_amp == 0 && (b->sma_amp_b.lpos > 1)))) { - a = fabs(b->sma_amp_b.sma); - if (a < AVMD_MIN_AMP) { - return 0; - } - rsd = sqrt(v) / a; - if (rsd < rsd_threshold) { - return 1; - } - } - return 0; + lpos = b->sma_b.lpos; + if ((lpos >= AVMD_BEEP_LEN(s->rate) / b->resolution) && ((s->settings.require_continuous_streak_amp == 1 && (b->sma_amp_b.lpos > s->settings.sample_n_continuous_streak_amp) && (b->samples_streak_amp == 0)) + || (s->settings.require_continuous_streak_amp == 0 && (b->sma_amp_b.lpos > 1)))) { + a = fabs(b->sma_amp_b.sma); + if (a < AVMD_MIN_AMP) { + return 0; + } + rsd = sqrt(v) / a; + if (rsd < rsd_threshold) { + return 1; + } + } + return 0; } static int avmd_decision_freq(const avmd_session_t *s, const struct avmd_buffer *b, double v, double rsd_threshold) { - double f, rsd; - size_t lpos; - f = AVMD_TO_HZ(s->rate, fabs(b->sma_b_fir.sma)); - if ((f < AVMD_MIN_FREQUENCY) || (f > AVMD_MAX_FREQUENCY)) { - return 0; - } - lpos = b->sma_b.lpos; - if ((lpos >= AVMD_BEEP_LEN(s->rate) / b->resolution) && ((s->settings.require_continuous_streak == 1 && (b->sma_b.lpos > s->settings.sample_n_continuous_streak) && (b->samples_streak == 0)) - || (s->settings.require_continuous_streak == 0 && (b->sma_b.lpos > 1)))) { - rsd = sqrt(v) / f; - if ((rsd < 0.3 * rsd_threshold) && (b->sma_amp_b.sma >= 0.005 * b->amplitude_max)) { - return 1; - } - if ((rsd < 0.6 * rsd_threshold) && (b->sma_amp_b.sma >= 0.01 * b->amplitude_max)) { - return 1; - } - if ((rsd < rsd_threshold) && (b->sma_amp_b.sma >= 0.015 * b->amplitude_max)) { - return 1; - } - } - return 0; + double f, rsd; + size_t lpos; + f = AVMD_TO_HZ(s->rate, fabs(b->sma_b_fir.sma)); + if ((f < AVMD_MIN_FREQUENCY) || (f > AVMD_MAX_FREQUENCY)) { + return 0; + } + lpos = b->sma_b.lpos; + if ((lpos >= AVMD_BEEP_LEN(s->rate) / b->resolution) && ((s->settings.require_continuous_streak == 1 && (b->sma_b.lpos > s->settings.sample_n_continuous_streak) && (b->samples_streak == 0)) + || (s->settings.require_continuous_streak == 0 && (b->sma_b.lpos > 1)))) { + rsd = sqrt(v) / f; + if ((rsd < 0.3 * rsd_threshold) && (b->sma_amp_b.sma >= 0.005 * b->amplitude_max)) { + return 1; + } + if ((rsd < 0.6 * rsd_threshold) && (b->sma_amp_b.sma >= 0.01 * b->amplitude_max)) { + return 1; + } + if ((rsd < rsd_threshold) && (b->sma_amp_b.sma >= 0.015 * b->amplitude_max)) { + return 1; + } + } + return 0; } static void avmd_report_detection(avmd_session_t *s, enum avmd_detection_mode mode, const struct avmd_detector *d) { - switch_channel_t *channel; - switch_time_t detection_time; - double f_sma = 0.0; - double v_amp = 9999.9, v_fir = 9999.9; + switch_channel_t *channel; + switch_time_t detection_time; + double f_sma = 0.0; + double v_amp = 9999.9, v_fir = 9999.9; - const struct avmd_buffer *b = &d->buffer; - const sma_buffer_t *sma_b_fir = &b->sma_b_fir; - const sma_buffer_t *sqa_b_fir = &b->sqa_b_fir; + const struct avmd_buffer *b = &d->buffer; + const sma_buffer_t *sma_b_fir = &b->sma_b_fir; + const sma_buffer_t *sqa_b_fir = &b->sqa_b_fir; - const sma_buffer_t *sma_amp_b = &b->sma_amp_b; - const sma_buffer_t *sqa_amp_b = &b->sqa_amp_b; + const sma_buffer_t *sma_amp_b = &b->sma_amp_b; + const sma_buffer_t *sqa_amp_b = &b->sqa_amp_b; - channel = switch_core_session_get_channel(s->session); + channel = switch_core_session_get_channel(s->session); - s->detection_stop_time = switch_micro_time_now(); /* stop detection timer */ - detection_time = s->detection_stop_time - s->detection_start_time; /* detection time length */ - switch_channel_set_variable_printf(channel, "avmd_total_time", "[%" PRId64 "]", detection_time / 1000); - switch_channel_execute_on(channel, "execute_on_avmd_beep"); - switch_channel_set_variable(channel, "avmd_detect", "TRUE"); - switch (mode) { + s->detection_stop_time = switch_micro_time_now(); /* stop detection timer */ + detection_time = s->detection_stop_time - s->detection_start_time; /* detection time length */ + switch_channel_set_variable_printf(channel, "avmd_total_time", "[%" PRId64 "]", detection_time / 1000); + switch_channel_execute_on(channel, "execute_on_avmd_beep"); + switch_channel_set_variable(channel, "avmd_detect", "TRUE"); + switch (mode) { - case AVMD_DETECT_AMP: - v_amp = sqa_amp_b->sma - (sma_amp_b->sma * sma_amp_b->sma); /* calculate variance of amplitude (biased estimator) */ - avmd_fire_event(AVMD_EVENT_BEEP, s->session, 0, 0, sma_amp_b->sma, v_amp, 0, 0, s->detection_start_time, s->detection_stop_time, 0, 0, b->resolution, b->offset, d->idx); - if (s->settings.report_status == 1) { - switch_log_printf(SWITCH_CHANNEL_SESSION_LOG(s->session), SWITCH_LOG_INFO, "<<< AVMD - Beep Detected [%u][%u][%u][%u]: amplitude = [%f](max [%f]) variance = [%f], detection time [%" PRId64 "] [us] >>>\n", - mode, b->resolution, b->offset, d->idx, sma_amp_b->sma, b->amplitude_max, v_amp, detection_time); - } - break; + case AVMD_DETECT_AMP: + v_amp = sqa_amp_b->sma - (sma_amp_b->sma * sma_amp_b->sma); /* calculate variance of amplitude (biased estimator) */ + avmd_fire_event(AVMD_EVENT_BEEP, s->session, 0, 0, sma_amp_b->sma, v_amp, 0, 0, s->detection_start_time, s->detection_stop_time, 0, 0, b->resolution, b->offset, d->idx); + if (s->settings.report_status == 1) { + switch_log_printf(SWITCH_CHANNEL_SESSION_LOG(s->session), SWITCH_LOG_INFO, "<<< AVMD - Beep Detected [%u][%u][%u][%u]: amplitude = [%f](max [%f]) variance = [%f], detection time [%" PRId64 "] [us] >>>\n", + mode, b->resolution, b->offset, d->idx, sma_amp_b->sma, b->amplitude_max, v_amp, detection_time); + } + break; - case AVMD_DETECT_FREQ: - f_sma = sma_b_fir->sma; - v_fir = sqa_b_fir->sma - (sma_b_fir->sma * sma_b_fir->sma); /* calculate variance of filtered samples */ - avmd_fire_event(AVMD_EVENT_BEEP, s->session, AVMD_TO_HZ(s->rate, f_sma), v_fir, 0, 0, 0, 0, s->detection_start_time, s->detection_stop_time, 0, 0, b->resolution, b->offset, d->idx); - if (s->settings.report_status == 1) { - switch_log_printf(SWITCH_CHANNEL_SESSION_LOG(s->session), SWITCH_LOG_INFO, "<<< AVMD - Beep Detected [%u][%u][%u][%u]: f = [%f] variance = [%f], detection time [%" PRId64 "] [us] >>>\n", - mode, b->resolution, b->offset, d->idx, AVMD_TO_HZ(s->rate, f_sma), v_fir, detection_time); - } - break; + case AVMD_DETECT_FREQ: + f_sma = sma_b_fir->sma; + v_fir = sqa_b_fir->sma - (sma_b_fir->sma * sma_b_fir->sma); /* calculate variance of filtered samples */ + avmd_fire_event(AVMD_EVENT_BEEP, s->session, AVMD_TO_HZ(s->rate, f_sma), v_fir, 0, 0, 0, 0, s->detection_start_time, s->detection_stop_time, 0, 0, b->resolution, b->offset, d->idx); + if (s->settings.report_status == 1) { + switch_log_printf(SWITCH_CHANNEL_SESSION_LOG(s->session), SWITCH_LOG_INFO, "<<< AVMD - Beep Detected [%u][%u][%u][%u]: f = [%f] variance = [%f], detection time [%" PRId64 "] [us] >>>\n", + mode, b->resolution, b->offset, d->idx, AVMD_TO_HZ(s->rate, f_sma), v_fir, detection_time); + } + break; - case AVMD_DETECT_BOTH: - v_amp = sqa_amp_b->sma - (sma_amp_b->sma * sma_amp_b->sma); /* calculate variance of amplitude (biased estimator) */ - f_sma = sma_b_fir->sma; - v_fir = sqa_b_fir->sma - (sma_b_fir->sma * sma_b_fir->sma); /* calculate variance of filtered samples */ - avmd_fire_event(AVMD_EVENT_BEEP, s->session, AVMD_TO_HZ(s->rate, f_sma), v_fir, sma_amp_b->sma, v_amp, 0, 0, s->detection_start_time, s->detection_stop_time, 0, 0, b->resolution, b->offset, d->idx); - if (s->settings.report_status == 1) { - switch_log_printf(SWITCH_CHANNEL_SESSION_LOG(s->session), SWITCH_LOG_INFO, "<<< AVMD - Beep Detected [%u][%u][%u][%u]: f = [%f] variance = [%f], amplitude = [%f](max [%f]) variance = [%f], detection time [%" PRId64 "] [us] >>>\n", - mode, b->resolution, b->offset, d->idx, AVMD_TO_HZ(s->rate, f_sma), v_fir, sma_amp_b->sma, b->amplitude_max, v_amp, detection_time); - } - break; + case AVMD_DETECT_BOTH: + v_amp = sqa_amp_b->sma - (sma_amp_b->sma * sma_amp_b->sma); /* calculate variance of amplitude (biased estimator) */ + f_sma = sma_b_fir->sma; + v_fir = sqa_b_fir->sma - (sma_b_fir->sma * sma_b_fir->sma); /* calculate variance of filtered samples */ + avmd_fire_event(AVMD_EVENT_BEEP, s->session, AVMD_TO_HZ(s->rate, f_sma), v_fir, sma_amp_b->sma, v_amp, 0, 0, s->detection_start_time, s->detection_stop_time, 0, 0, b->resolution, b->offset, d->idx); + if (s->settings.report_status == 1) { + switch_log_printf(SWITCH_CHANNEL_SESSION_LOG(s->session), SWITCH_LOG_INFO, "<<< AVMD - Beep Detected [%u][%u][%u][%u]: f = [%f] variance = [%f], amplitude = [%f](max [%f]) variance = [%f], detection time [%" PRId64 "] [us] >>>\n", + mode, b->resolution, b->offset, d->idx, AVMD_TO_HZ(s->rate, f_sma), v_fir, sma_amp_b->sma, b->amplitude_max, v_amp, detection_time); + } + break; - default: - break; - } - s->state.beep_state = BEEP_DETECTED; + default: + break; + } + s->state.beep_state = BEEP_DETECTED; } static uint8_t avmd_detection_in_progress(avmd_session_t *s) { - uint8_t idx = 0; - while (idx < (s->settings.detectors_n + s->settings.detectors_lagged_n)) { - switch_mutex_lock(s->detectors[idx].mutex); - if (s->detectors[idx].flag_processing_done == 0) { - switch_mutex_unlock(s->detectors[idx].mutex); - return 1; - } - switch_mutex_unlock(s->detectors[idx].mutex); - ++idx; - } - return 0; + uint8_t idx = 0; + while (idx < (s->settings.detectors_n + s->settings.detectors_lagged_n)) { + switch_mutex_lock(s->detectors[idx].mutex); + if (s->detectors[idx].flag_processing_done == 0) { + switch_mutex_unlock(s->detectors[idx].mutex); + return 1; + } + switch_mutex_unlock(s->detectors[idx].mutex); + ++idx; + } + return 0; } static enum avmd_detection_mode avmd_detection_result(avmd_session_t *s) { - enum avmd_detection_mode res; - uint8_t idx = 0; - while (idx < (s->settings.detectors_n + s->settings.detectors_lagged_n)) { - res = s->detectors[idx].result; - if (res != AVMD_DETECT_NONE) { - avmd_report_detection(s, res, &s->detectors[idx]); - return res; - } - ++idx; - } - return AVMD_DETECT_NONE; + enum avmd_detection_mode res; + uint8_t idx = 0; + while (idx < (s->settings.detectors_n + s->settings.detectors_lagged_n)) { + res = s->detectors[idx].result; + if (res != AVMD_DETECT_NONE) { + avmd_report_detection(s, res, &s->detectors[idx]); + return res; + } + ++idx; + } + return AVMD_DETECT_NONE; } /*! \brief Process one frame of data with avmd algorithm. @@ -2051,258 +2051,258 @@ avmd_detection_result(avmd_session_t *s) { * @param frame An audio frame. */ static void avmd_process(avmd_session_t *s, switch_frame_t *frame, uint8_t direction) { - circ_buffer_t *b; - uint8_t idx; - struct avmd_detector *d; + circ_buffer_t *b; + uint8_t idx; + struct avmd_detector *d; - b = &s->b; + b = &s->b; - switch_mutex_lock(s->mutex_detectors_done); - while (avmd_detection_in_progress(s) == 1) { - switch_thread_cond_wait(s->cond_detectors_done, s->mutex_detectors_done); - } - switch_mutex_unlock(s->mutex_detectors_done); + switch_mutex_lock(s->mutex_detectors_done); + while (avmd_detection_in_progress(s) == 1) { + switch_thread_cond_wait(s->cond_detectors_done, s->mutex_detectors_done); + } + switch_mutex_unlock(s->mutex_detectors_done); - if (s->state.beep_state == BEEP_DETECTED) { /* If beep has already been detected skip the CPU heavy stuff */ - return; - } + if (s->state.beep_state == BEEP_DETECTED) { /* If beep has already been detected skip the CPU heavy stuff */ + return; + } - if (s->frame_n_to_skip > 0) { - s->frame_n_to_skip--; - return; - } + if (s->frame_n_to_skip > 0) { + s->frame_n_to_skip--; + return; + } if (s->settings.debug) { switch_log_printf(SWITCH_CHANNEL_SESSION_LOG(s->session), SWITCH_LOG_INFO, "AVMD: processing frame [%zu], direction=%s\n", s->frame_n, direction == AVMD_READ_REPLACE ? "READ" : "WRITE"); } - if (s->detection_start_time == 0) { - s->detection_start_time = switch_micro_time_now(); /* start detection timer */ - } + if (s->detection_start_time == 0) { + s->detection_start_time = switch_micro_time_now(); /* start detection timer */ + } - INSERT_INT16_FRAME(b, (int16_t *)(frame->data), frame->samples); /* Insert frame of 16 bit samples into buffer */ + INSERT_INT16_FRAME(b, (int16_t *)(frame->data), frame->samples); /* Insert frame of 16 bit samples into buffer */ - idx = 0; - while (idx < (s->settings.detectors_n + s->settings.detectors_lagged_n)) { - d = &s->detectors[idx]; - switch_mutex_lock(d->mutex); - d = &s->detectors[idx]; - if (d->result == AVMD_DETECT_NONE) { - d->flag_processing_done = 0; - d->flag_should_exit = 0; - d->samples = (s->frame_n == 0 ? frame->samples - AVMD_P : frame->samples); - switch_thread_cond_signal(d->cond_start_processing); - } - switch_mutex_unlock(d->mutex); - ++idx; - } + idx = 0; + while (idx < (s->settings.detectors_n + s->settings.detectors_lagged_n)) { + d = &s->detectors[idx]; + switch_mutex_lock(d->mutex); + d = &s->detectors[idx]; + if (d->result == AVMD_DETECT_NONE) { + d->flag_processing_done = 0; + d->flag_should_exit = 0; + d->samples = (s->frame_n == 0 ? frame->samples - AVMD_P : frame->samples); + switch_thread_cond_signal(d->cond_start_processing); + } + switch_mutex_unlock(d->mutex); + ++idx; + } - switch_mutex_lock(s->mutex_detectors_done); - while (avmd_detection_in_progress(s) == 1) { - switch_thread_cond_wait(s->cond_detectors_done, s->mutex_detectors_done); - } - avmd_detection_result(s); - switch_mutex_unlock(s->mutex_detectors_done); + switch_mutex_lock(s->mutex_detectors_done); + while (avmd_detection_in_progress(s) == 1) { + switch_thread_cond_wait(s->cond_detectors_done, s->mutex_detectors_done); + } + avmd_detection_result(s); + switch_mutex_unlock(s->mutex_detectors_done); - ++s->frame_n; - if (s->frame_n == 1) { - s->pos += frame->samples - AVMD_P; - } else { - s->pos += frame->samples; - } - s->pos &= b->mask; + ++s->frame_n; + if (s->frame_n == 1) { + s->pos += frame->samples - AVMD_P; + } else { + s->pos += frame->samples; + } + s->pos &= b->mask; - return; + return; } static void avmd_reloadxml_event_handler(switch_event_t *event) { - avmd_load_xml_configuration(avmd_globals.mutex); + avmd_load_xml_configuration(avmd_globals.mutex); } static enum avmd_detection_mode avmd_process_sample(avmd_session_t *s, circ_buffer_t *b, size_t sample_n, size_t pos, struct avmd_detector *d) { - struct avmd_buffer *buffer = &d->buffer; - uint16_t sample_to_skip_n = s->settings.sample_n_to_skip; - enum avmd_detection_mode mode = s->settings.mode; - uint8_t valid_amplitude = 1, valid_omega = 1; - double omega = 0.0, amplitude = 0.0; - double f = 0.0, f_fir = 0.0; - double v_amp = 9999.9, v_fir = 9999.9; + struct avmd_buffer *buffer = &d->buffer; + uint16_t sample_to_skip_n = s->settings.sample_n_to_skip; + enum avmd_detection_mode mode = s->settings.mode; + uint8_t valid_amplitude = 1, valid_omega = 1; + double omega = 0.0, amplitude = 0.0; + double f = 0.0, f_fir = 0.0; + double v_amp = 9999.9, v_fir = 9999.9; - sma_buffer_t *sma_b = &buffer->sma_b; - sma_buffer_t *sqa_b = &buffer->sqa_b; + sma_buffer_t *sma_b = &buffer->sma_b; + sma_buffer_t *sqa_b = &buffer->sqa_b; - sma_buffer_t *sma_b_fir = &buffer->sma_b_fir; - sma_buffer_t *sqa_b_fir = &buffer->sqa_b_fir; + sma_buffer_t *sma_b_fir = &buffer->sma_b_fir; + sma_buffer_t *sqa_b_fir = &buffer->sqa_b_fir; - sma_buffer_t *sma_amp_b = &buffer->sma_amp_b; - sma_buffer_t *sqa_amp_b = &buffer->sqa_amp_b; + sma_buffer_t *sma_amp_b = &buffer->sma_amp_b; + sma_buffer_t *sqa_amp_b = &buffer->sqa_amp_b; - if (sample_to_skip_n > 0) { - sample_to_skip_n--; - valid_amplitude = 0; - valid_omega = 0; - return AVMD_DETECT_NONE; - } + if (sample_to_skip_n > 0) { + sample_to_skip_n--; + valid_amplitude = 0; + valid_omega = 0; + return AVMD_DETECT_NONE; + } - omega = avmd_desa2_tweaked(b, pos + sample_n, &litude); + omega = avmd_desa2_tweaked(b, pos + sample_n, &litude); - if (mode == AVMD_DETECT_AMP || mode == AVMD_DETECT_BOTH) { - if (ISNAN(amplitude) || ISINF(amplitude)) { - valid_amplitude = 0; - if (s->settings.require_continuous_streak_amp == 1) { - RESET_SMA_BUFFER(sma_amp_b); - RESET_SMA_BUFFER(sqa_amp_b); - buffer->samples_streak_amp = s->settings.sample_n_continuous_streak_amp; - sample_to_skip_n = s->settings.sample_n_to_skip; - } - } else { - if (ISINF(amplitude)) { - amplitude = buffer->amplitude_max; - } - if (valid_amplitude == 1) { - APPEND_SMA_VAL(sma_amp_b, amplitude); /* append amplitude */ - APPEND_SMA_VAL(sqa_amp_b, amplitude * amplitude); - if (s->settings.require_continuous_streak_amp == 1) { - if (buffer->samples_streak_amp > 0) { - --buffer->samples_streak_amp; - valid_amplitude = 0; - } - } - } - if (sma_amp_b->sma > buffer->amplitude_max) { - buffer->amplitude_max = sma_amp_b->sma; - } - } - } + if (mode == AVMD_DETECT_AMP || mode == AVMD_DETECT_BOTH) { + if (ISNAN(amplitude) || ISINF(amplitude)) { + valid_amplitude = 0; + if (s->settings.require_continuous_streak_amp == 1) { + RESET_SMA_BUFFER(sma_amp_b); + RESET_SMA_BUFFER(sqa_amp_b); + buffer->samples_streak_amp = s->settings.sample_n_continuous_streak_amp; + sample_to_skip_n = s->settings.sample_n_to_skip; + } + } else { + if (ISINF(amplitude)) { + amplitude = buffer->amplitude_max; + } + if (valid_amplitude == 1) { + APPEND_SMA_VAL(sma_amp_b, amplitude); /* append amplitude */ + APPEND_SMA_VAL(sqa_amp_b, amplitude * amplitude); + if (s->settings.require_continuous_streak_amp == 1) { + if (buffer->samples_streak_amp > 0) { + --buffer->samples_streak_amp; + valid_amplitude = 0; + } + } + } + if (sma_amp_b->sma > buffer->amplitude_max) { + buffer->amplitude_max = sma_amp_b->sma; + } + } + } - if (mode == AVMD_DETECT_FREQ || mode == AVMD_DETECT_BOTH) { - if (ISNAN(omega)) { - valid_omega = 0; - if (s->settings.require_continuous_streak == 1) { - RESET_SMA_BUFFER(sma_b); - RESET_SMA_BUFFER(sqa_b); - RESET_SMA_BUFFER(sma_b_fir); - RESET_SMA_BUFFER(sqa_b_fir); - buffer->samples_streak = s->settings.sample_n_continuous_streak; - sample_to_skip_n = s->settings.sample_n_to_skip; - } - sample_to_skip_n = s->settings.sample_n_to_skip; - } else if (omega < -0.99999 || omega > 0.99999) { - valid_omega = 0; - if (s->settings.require_continuous_streak == 1) { - RESET_SMA_BUFFER(sma_b); - RESET_SMA_BUFFER(sqa_b); - RESET_SMA_BUFFER(sma_b_fir); - RESET_SMA_BUFFER(sqa_b_fir); - buffer->samples_streak = s->settings.sample_n_continuous_streak; - sample_to_skip_n = s->settings.sample_n_to_skip; - } - } else { - if (valid_omega) { + if (mode == AVMD_DETECT_FREQ || mode == AVMD_DETECT_BOTH) { + if (ISNAN(omega)) { + valid_omega = 0; + if (s->settings.require_continuous_streak == 1) { + RESET_SMA_BUFFER(sma_b); + RESET_SMA_BUFFER(sqa_b); + RESET_SMA_BUFFER(sma_b_fir); + RESET_SMA_BUFFER(sqa_b_fir); + buffer->samples_streak = s->settings.sample_n_continuous_streak; + sample_to_skip_n = s->settings.sample_n_to_skip; + } + sample_to_skip_n = s->settings.sample_n_to_skip; + } else if (omega < -0.99999 || omega > 0.99999) { + valid_omega = 0; + if (s->settings.require_continuous_streak == 1) { + RESET_SMA_BUFFER(sma_b); + RESET_SMA_BUFFER(sqa_b); + RESET_SMA_BUFFER(sma_b_fir); + RESET_SMA_BUFFER(sqa_b_fir); + buffer->samples_streak = s->settings.sample_n_continuous_streak; + sample_to_skip_n = s->settings.sample_n_to_skip; + } + } else { + if (valid_omega) { #if !defined(WIN32) && defined(AVMD_FAST_MATH) - f = 0.5 * (double) fast_acosf((float)omega); + f = 0.5 * (double) fast_acosf((float)omega); #else - f = 0.5 * acos(omega); + f = 0.5 * acos(omega); #endif /* !WIN32 && AVMD_FAST_MATH */ - f_fir = sma_b->pos > 1 ? (AVMD_MEDIAN_FILTER(sma_b->data[sma_b->pos - 2], sma_b->data[sma_b->pos - 1], f)) : f; + f_fir = sma_b->pos > 1 ? (AVMD_MEDIAN_FILTER(sma_b->data[sma_b->pos - 2], sma_b->data[sma_b->pos - 1], f)) : f; - APPEND_SMA_VAL(sma_b, f); /* append frequency */ - APPEND_SMA_VAL(sqa_b, f * f); - APPEND_SMA_VAL(sma_b_fir, f_fir); /* append filtered frequency */ - APPEND_SMA_VAL(sqa_b_fir, f_fir * f_fir); - if (s->settings.require_continuous_streak == 1) { - if (buffer->samples_streak > 0) { - --buffer->samples_streak; - valid_omega = 0; - } - } - } - } - } + APPEND_SMA_VAL(sma_b, f); /* append frequency */ + APPEND_SMA_VAL(sqa_b, f * f); + APPEND_SMA_VAL(sma_b_fir, f_fir); /* append filtered frequency */ + APPEND_SMA_VAL(sqa_b_fir, f_fir * f_fir); + if (s->settings.require_continuous_streak == 1) { + if (buffer->samples_streak > 0) { + --buffer->samples_streak; + valid_omega = 0; + } + } + } + } + } - if (((mode == AVMD_DETECT_AMP) || (mode == AVMD_DETECT_BOTH)) && (valid_amplitude == 1)) { - v_amp = sqa_amp_b->sma - (sma_amp_b->sma * sma_amp_b->sma); /* calculate variance of amplitude (biased estimator) */ - if ((mode == AVMD_DETECT_AMP) && (avmd_decision_amplitude(s, buffer, v_amp, AVMD_AMPLITUDE_RSD_THRESHOLD) == 1)) { - return AVMD_DETECT_AMP; - } - } - if (((mode == AVMD_DETECT_FREQ) || (mode == AVMD_DETECT_BOTH)) && (valid_omega == 1)) { - v_fir = sqa_b_fir->sma - (sma_b_fir->sma * sma_b_fir->sma); /* calculate variance of filtered samples */ - if ((mode == AVMD_DETECT_FREQ) && (avmd_decision_freq(s, buffer, v_fir, AVMD_VARIANCE_RSD_THRESHOLD) == 1)) { - return AVMD_DETECT_FREQ; - } - if (mode == AVMD_DETECT_BOTH) { - if ((avmd_decision_amplitude(s, buffer, v_amp, AVMD_AMPLITUDE_RSD_THRESHOLD) == 1) && (avmd_decision_freq(s, buffer, v_fir, AVMD_VARIANCE_RSD_THRESHOLD) == 1)) { - return AVMD_DETECT_BOTH; - } - } - } - return AVMD_DETECT_NONE; + if (((mode == AVMD_DETECT_AMP) || (mode == AVMD_DETECT_BOTH)) && (valid_amplitude == 1)) { + v_amp = sqa_amp_b->sma - (sma_amp_b->sma * sma_amp_b->sma); /* calculate variance of amplitude (biased estimator) */ + if ((mode == AVMD_DETECT_AMP) && (avmd_decision_amplitude(s, buffer, v_amp, AVMD_AMPLITUDE_RSD_THRESHOLD) == 1)) { + return AVMD_DETECT_AMP; + } + } + if (((mode == AVMD_DETECT_FREQ) || (mode == AVMD_DETECT_BOTH)) && (valid_omega == 1)) { + v_fir = sqa_b_fir->sma - (sma_b_fir->sma * sma_b_fir->sma); /* calculate variance of filtered samples */ + if ((mode == AVMD_DETECT_FREQ) && (avmd_decision_freq(s, buffer, v_fir, AVMD_VARIANCE_RSD_THRESHOLD) == 1)) { + return AVMD_DETECT_FREQ; + } + if (mode == AVMD_DETECT_BOTH) { + if ((avmd_decision_amplitude(s, buffer, v_amp, AVMD_AMPLITUDE_RSD_THRESHOLD) == 1) && (avmd_decision_freq(s, buffer, v_fir, AVMD_VARIANCE_RSD_THRESHOLD) == 1)) { + return AVMD_DETECT_BOTH; + } + } + } + return AVMD_DETECT_NONE; } static void* SWITCH_THREAD_FUNC avmd_detector_func(switch_thread_t *thread, void *arg) { - size_t sample_n = 0, samples = AVMD_P; - size_t pos; - uint8_t resolution, offset; - avmd_session_t *s; - enum avmd_detection_mode res = AVMD_DETECT_NONE; - struct avmd_detector *d; + size_t sample_n = 0, samples = AVMD_P; + size_t pos; + uint8_t resolution, offset; + avmd_session_t *s; + enum avmd_detection_mode res = AVMD_DETECT_NONE; + struct avmd_detector *d; - d = (struct avmd_detector*) arg; - s = d->s; - pos = s->pos; - while (1) { - switch_mutex_lock(d->mutex); - while ((d->flag_processing_done == 1) && (d->flag_should_exit == 0)) { - switch_thread_cond_wait(d->cond_start_processing, d->mutex); - } - /* master set processing_done flag to 0 or thread should exit */ - if (d->flag_should_exit == 1) { - d->flag_processing_done = 1; - goto end; - } - resolution = d->buffer.resolution; - offset = d->buffer.offset; - samples = d->samples; + d = (struct avmd_detector*) arg; + s = d->s; + pos = s->pos; + while (1) { + switch_mutex_lock(d->mutex); + while ((d->flag_processing_done == 1) && (d->flag_should_exit == 0)) { + switch_thread_cond_wait(d->cond_start_processing, d->mutex); + } + /* master set processing_done flag to 0 or thread should exit */ + if (d->flag_should_exit == 1) { + d->flag_processing_done = 1; + goto end; + } + resolution = d->buffer.resolution; + offset = d->buffer.offset; + samples = d->samples; - if (d->lagged == 1) { - if (d->lag > 0) { - --d->lag; - goto done; - } - pos += AVMD_P; - } + if (d->lagged == 1) { + if (d->lag > 0) { + --d->lag; + goto done; + } + pos += AVMD_P; + } - switch_mutex_unlock(d->mutex); - sample_n = 1; - while (sample_n <= samples) { - if (((sample_n + offset) % resolution) == 0) { - res = avmd_process_sample(d->s, &s->b, sample_n, pos, d); - if (res != AVMD_DETECT_NONE) { - break; - } - } - ++sample_n; - } - switch_mutex_lock(d->mutex); + switch_mutex_unlock(d->mutex); + sample_n = 1; + while (sample_n <= samples) { + if (((sample_n + offset) % resolution) == 0) { + res = avmd_process_sample(d->s, &s->b, sample_n, pos, d); + if (res != AVMD_DETECT_NONE) { + break; + } + } + ++sample_n; + } + switch_mutex_lock(d->mutex); done: - d->flag_processing_done = 1; - d->result = res; - switch_mutex_unlock(d->mutex); + d->flag_processing_done = 1; + d->result = res; + switch_mutex_unlock(d->mutex); - switch_mutex_lock(s->mutex_detectors_done); - switch_thread_cond_signal(s->cond_detectors_done); - switch_mutex_unlock(s->mutex_detectors_done); - } - return NULL; + switch_mutex_lock(s->mutex_detectors_done); + switch_thread_cond_signal(s->cond_detectors_done); + switch_mutex_unlock(s->mutex_detectors_done); + } + return NULL; end: - switch_mutex_unlock(d->mutex); - return NULL; + switch_mutex_unlock(d->mutex); + return NULL; } diff --git a/src/mod/applications/mod_avmd/scripts/avmd_get_events.pl b/src/mod/applications/mod_avmd/scripts/avmd_get_events.pl index 80d0caeb6d..f66f41a6d8 100644 --- a/src/mod/applications/mod_avmd/scripts/avmd_get_events.pl +++ b/src/mod/applications/mod_avmd/scripts/avmd_get_events.pl @@ -19,18 +19,18 @@ my $pass = "ClueCon"; my $format = "plain"; if ($#ARGV + 1 eq 1) { - $format = $ARGV[0]; - print "Using format: [" .$format ."]\n"; + $format = $ARGV[0]; + print "Using format: [" .$format ."]\n"; } -my $con = new ESL::ESLconnection($host, $port, $pass); +my $con = new ESL::ESLconnection($host, $port, $pass); if (!$con) { - die "Unable to establish connection to $host:$port\n"; + die "Unable to establish connection to $host:$port\n"; } if ($con->connected()) { - print "OK, Connected.\n"; + print "OK, Connected.\n"; } else { - die "Conenction failure.\n"; + die "Conenction failure.\n"; } print "Subscribing to avmd events...\n"; @@ -40,17 +40,17 @@ $con->events("plain", "CUSTOM avmd::beep"); print "Waiting for the events...\n"; while($con->connected()) { - my $e = $con->recvEvent(); - my $avmd_event_type = ""; - $avmd_event_type = $e->getHeader("Event-Subclass"); - if ($avmd_event_type eq 'avmd::start') { # mark nicely the start of new session and event streak - most likely there will be other events from this session coming after this one - print "\n--------------------\n\n"; - } - if ($e) { - my $body = $e->serialize($format); - print $body; - print "\n\n"; - } + my $e = $con->recvEvent(); + my $avmd_event_type = ""; + $avmd_event_type = $e->getHeader("Event-Subclass"); + if ($avmd_event_type eq 'avmd::start') { # mark nicely the start of new session and event streak - most likely there will be other events from this session coming after this one + print "\n--------------------\n\n"; + } + if ($e) { + my $body = $e->serialize($format); + print $body; + print "\n\n"; + } } print "Disconnected.\n\n"; diff --git a/src/mod/applications/mod_avmd/scripts/avmd_originate.pl b/src/mod/applications/mod_avmd/scripts/avmd_originate.pl index 9cbc98ea5e..2906e4af41 100644 --- a/src/mod/applications/mod_avmd/scripts/avmd_originate.pl +++ b/src/mod/applications/mod_avmd/scripts/avmd_originate.pl @@ -25,21 +25,21 @@ my $callerid; if ($#ARGV + 1 eq 2) { - $dest = $ARGV[0]; - $callerid = $ARGV[1]; - print "Dialing [" .$dest ."] as " .$callerid ."]\n"; + $dest = $ARGV[0]; + $callerid = $ARGV[1]; + print "Dialing [" .$dest ."] as " .$callerid ."]\n"; } else { - die "Please specify destination number and caller id\n"; + die "Please specify destination number and caller id\n"; } my $con = new ESL::ESLconnection($host, $port, $pass); if (!$con) { - die "Unable to establish connection to $host:$port\n"; + die "Unable to establish connection to $host:$port\n"; } if ($con->connected()) { - print "OK, Connected.\n"; + print "OK, Connected.\n"; } else { - die "Connection failure.\n"; + die "Connection failure.\n"; } print "Subscribing to avmd events...\n"; @@ -48,42 +48,42 @@ $con->events("plain", "CUSTOM avmd::stop"); $con->events("plain", "CUSTOM avmd::beep"); while($con->connected()) { - test_once($dest, $callerid); - return 0; + test_once($dest, $callerid); + return 0; } print "Disconnected.\n\n"; sub test_once { - my ($dest, $callerid) = @_; - my $originate_string = - 'originate ' . - '{ignore_early_media=true,' . - 'origination_uuid=%s,' . - 'originate_timeout=60,' . - 'origination_caller_id_number=' . $callerid . ',' . - 'origination_caller_id_name=' . $callerid . '}'; + my ($dest, $callerid) = @_; + my $originate_string = + 'originate ' . + '{ignore_early_media=true,' . + 'origination_uuid=%s,' . + 'originate_timeout=60,' . + 'origination_caller_id_number=' . $callerid . ',' . + 'origination_caller_id_name=' . $callerid . '}'; - if(defined($endpoint)) { - $originate_string .= $endpoint; - } else { - $originate_string .= 'loopback/' . $dest . '/' . $context; - } - $originate_string .= ' ' . '&playback(' . $playback . ')'; + if(defined($endpoint)) { + $originate_string .= $endpoint; + } else { + $originate_string .= 'loopback/' . $dest . '/' . $context; + } + $originate_string .= ' ' . '&playback(' . $playback . ')'; - my $uuid = $con->api('create_uuid')->getBody(); - my ($time_epoch, $time_hires) = Time::HiRes::gettimeofday(); - printf("Calling with uuid [%s] [%s]... [%s]\n", $uuid, POSIX::strftime('%Y-%m-%d %H:%M:%S', localtime($time_epoch)), $originate_string); + my $uuid = $con->api('create_uuid')->getBody(); + my ($time_epoch, $time_hires) = Time::HiRes::gettimeofday(); + printf("Calling with uuid [%s] [%s]... [%s]\n", $uuid, POSIX::strftime('%Y-%m-%d %H:%M:%S', localtime($time_epoch)), $originate_string); - $con->bgapi(sprintf($originate_string, $uuid)); + $con->bgapi(sprintf($originate_string, $uuid)); - print "Waiting for the events...\n\n"; - while($con->connected()) { - my $e = $con->recvEvent(); - if ($e) { - my $body = $e->serialize('plain'); - print $body; - print "\n\n"; - } - } + print "Waiting for the events...\n\n"; + while($con->connected()) { + my $e = $con->recvEvent(); + if ($e) { + my $body = $e->serialize('plain'); + print $body; + print "\n\n"; + } + } } diff --git a/src/mod/applications/mod_avmd/scripts/avmd_originate_multiple.pl b/src/mod/applications/mod_avmd/scripts/avmd_originate_multiple.pl index 223cedc557..758c89deb1 100644 --- a/src/mod/applications/mod_avmd/scripts/avmd_originate_multiple.pl +++ b/src/mod/applications/mod_avmd/scripts/avmd_originate_multiple.pl @@ -32,55 +32,55 @@ my $idx = 0; if ($#ARGV + 1 eq 3) { - $dest = $ARGV[0]; - $callerid = $ARGV[1]; - $thread_n = $ARGV[2]; - print "Dialing [" .$thread_n ."] calls simultaneously to[" .$dest ."] as [" .$callerid ."]\n"; + $dest = $ARGV[0]; + $callerid = $ARGV[1]; + $thread_n = $ARGV[2]; + print "Dialing [" .$thread_n ."] calls simultaneously to[" .$dest ."] as [" .$callerid ."]\n"; } else { - die "Please specify destination number, caller id and number of calls to make\n\nExample:\n./avmd_originate_multiple.pl EXTENSION CALLER NUMBER_OF_CALLS"; + die "Please specify destination number, caller id and number of calls to make\n\nExample:\n./avmd_originate_multiple.pl EXTENSION CALLER NUMBER_OF_CALLS"; } my $con = new ESL::ESLconnection($host, $port, $pass); if (!$con) { - die "Unable to establish connection to $host:$port\n"; + die "Unable to establish connection to $host:$port\n"; } if ($con->connected()) { - print "OK, Connected.\n"; + print "OK, Connected.\n"; } else { - die "Connection failure.\n"; + die "Connection failure.\n"; } while($con->connected() && ($idx < $thread_n)) { - call_once($dest, $callerid, $idx); - $idx++; - Time::HiRes::sleep(0.11); # avoid switch_core_session.c:2265 Throttle Error! 33, switch_time.c:1227 Over Session Rate of 30! + call_once($dest, $callerid, $idx); + $idx++; + Time::HiRes::sleep(0.11); # avoid switch_core_session.c:2265 Throttle Error! 33, switch_time.c:1227 Over Session Rate of 30! } print "Disconnected.\n\n"; sub call_once { - my ($dest, $callerid, $idx) = @_; - my $originate_string = - 'originate ' . - '{ignore_early_media=true,' . - 'originator_codec=PCMA,' . - 'origination_uuid=%s,' . - 'originate_timeout=60,' . - 'origination_caller_id_number=' . $callerid . ',' . - 'origination_caller_id_name=' . $callerid . '}'; + my ($dest, $callerid, $idx) = @_; + my $originate_string = + 'originate ' . + '{ignore_early_media=true,' . + 'originator_codec=PCMA,' . + 'origination_uuid=%s,' . + 'originate_timeout=60,' . + 'origination_caller_id_number=' . $callerid . ',' . + 'origination_caller_id_name=' . $callerid . '}'; - if(defined($endpoint)) { - $originate_string = ''; - $originate_string .= $endpoint; - } else { - $originate_string .= 'loopback/' . $dest . '/' . $context; - $originate_string .= ' ' . '&playback(' . $playback . ')'; - } + if(defined($endpoint)) { + $originate_string = ''; + $originate_string .= $endpoint; + } else { + $originate_string .= 'loopback/' . $dest . '/' . $context; + $originate_string .= ' ' . '&playback(' . $playback . ')'; + } - my $uuid = $con->api('create_uuid')->getBody(); - my ($time_epoch, $time_hires) = Time::HiRes::gettimeofday(); - printf("[%s]\tCalling with uuid [%s] [%s]... [%s]\n", $idx + 1, $uuid, POSIX::strftime('%Y-%m-%d %H:%M:%S', localtime($time_epoch)), $originate_string); + my $uuid = $con->api('create_uuid')->getBody(); + my ($time_epoch, $time_hires) = Time::HiRes::gettimeofday(); + printf("[%s]\tCalling with uuid [%s] [%s]... [%s]\n", $idx + 1, $uuid, POSIX::strftime('%Y-%m-%d %H:%M:%S', localtime($time_epoch)), $originate_string); - $con->bgapi(sprintf($originate_string, $uuid)); - $con->api('uuid_setvar ' . $uuid .' execute_on_answer avmd_start'); + $con->bgapi(sprintf($originate_string, $uuid)); + $con->api('uuid_setvar ' . $uuid .' execute_on_answer avmd_start'); } diff --git a/src/mod/applications/mod_avmd/scripts/avmd_originate_multiple_loopback.pl b/src/mod/applications/mod_avmd/scripts/avmd_originate_multiple_loopback.pl index 8eb791d13c..1831d09d5f 100644 --- a/src/mod/applications/mod_avmd/scripts/avmd_originate_multiple_loopback.pl +++ b/src/mod/applications/mod_avmd/scripts/avmd_originate_multiple_loopback.pl @@ -27,51 +27,51 @@ my $idx = 0; if ($#ARGV + 1 eq 3) { - $dest = $ARGV[0]; - $callerid = $ARGV[1]; - $thread_n = $ARGV[2]; - print "Dialing [" .$thread_n ."] calls simultaneously to [loopback][" .$dest ."] as [" .$callerid ."]\n"; + $dest = $ARGV[0]; + $callerid = $ARGV[1]; + $thread_n = $ARGV[2]; + print "Dialing [" .$thread_n ."] calls simultaneously to [loopback][" .$dest ."] as [" .$callerid ."]\n"; } else { - die "Please specify destination number, caller id and number of calls to make\n"; + die "Please specify destination number, caller id and number of calls to make\n"; } my $con = new ESL::ESLconnection($host, $port, $pass); if (!$con) { - die "Unable to establish connection to $host:$port\n"; + die "Unable to establish connection to $host:$port\n"; } if ($con->connected()) { - print "OK, Connected.\n"; + print "OK, Connected.\n"; } else { - die "Connection failure.\n"; + die "Connection failure.\n"; } while($con->connected() && ($idx < $thread_n)) { - call_once($dest, $callerid, $idx); - $idx++; - Time::HiRes::sleep(0.11); # avoid switch_core_session.c:2265 Throttle Error! 33, switch_time.c:1227 Over Session Rate of 30! + call_once($dest, $callerid, $idx); + $idx++; + Time::HiRes::sleep(0.11); # avoid switch_core_session.c:2265 Throttle Error! 33, switch_time.c:1227 Over Session Rate of 30! } print "Disconnected.\n\n"; sub call_once { - my ($dest, $callerid, $idx) = @_; - my $uuid = - my $originate_string = - 'originate ' . - '{ignore_early_media=true,' . - 'originator_codec=PCMA,' . - 'origination_uuid=%s,' . - 'originate_timeout=60,' . - 'origination_caller_id_number=' . $callerid . ',' . - 'origination_caller_id_name=' . $callerid . '}'; + my ($dest, $callerid, $idx) = @_; + my $uuid = + my $originate_string = + 'originate ' . + '{ignore_early_media=true,' . + 'originator_codec=PCMA,' . + 'origination_uuid=%s,' . + 'originate_timeout=60,' . + 'origination_caller_id_number=' . $callerid . ',' . + 'origination_caller_id_name=' . $callerid . '}'; - $originate_string .= 'loopback/' . $dest . '/' . $context; - $originate_string .= ' ' . '&playback(' . $playback . ')'; + $originate_string .= 'loopback/' . $dest . '/' . $context; + $originate_string .= ' ' . '&playback(' . $playback . ')'; - my $uuid = $con->api('create_uuid')->getBody(); - my ($time_epoch, $time_hires) = Time::HiRes::gettimeofday(); - printf("[%s]\tCalling with uuid [%s] [%s]... [%s]\n", $idx + 1, $uuid, POSIX::strftime('%Y-%m-%d %H:%M:%S', localtime($time_epoch)), $originate_string); + my $uuid = $con->api('create_uuid')->getBody(); + my ($time_epoch, $time_hires) = Time::HiRes::gettimeofday(); + printf("[%s]\tCalling with uuid [%s] [%s]... [%s]\n", $idx + 1, $uuid, POSIX::strftime('%Y-%m-%d %H:%M:%S', localtime($time_epoch)), $originate_string); - $con->bgapi(sprintf($originate_string, $uuid)); - $con->api('uuid_setvar ' . $uuid .' execute_on_answer avmd_start'); + $con->bgapi(sprintf($originate_string, $uuid)); + $con->api('uuid_setvar ' . $uuid .' execute_on_answer avmd_start'); } diff --git a/src/mod/applications/mod_avmd/scripts/avmd_test.pl b/src/mod/applications/mod_avmd/scripts/avmd_test.pl index c6f63e1c09..a32bf03a53 100755 --- a/src/mod/applications/mod_avmd/scripts/avmd_test.pl +++ b/src/mod/applications/mod_avmd/scripts/avmd_test.pl @@ -1,14 +1,14 @@ #!/usr/bin/perl -w -#brief Test module avmd by calling voicemails from avmd test suite -# and print detection results to the console. -#author Piotr Gregor -#details If you are testing serving voicemails from dialplan then avmd -# must be set to inbound mode, either globally (by avmd set inbound -# in fs_cli) or in dialplan settings ( +#details If you are testing serving voicemails from dialplan then avmd +# must be set to inbound mode, either globally (by avmd set inbound +# in fs_cli) or in dialplan settings ( pairs my %numbers = ( - 503 => "NOTDETECTED", # dual frequency (similar to single freq with varying amplitude), mode [0] AVMD_DETECT_AMP - 504 => "NOTDETECTED", - 505 => "NOTDETECTED", - 506 => "NOTDETECTED", - 507 => "NOTDETECTED", - 508 => "NOTDETECTED", - 509 => "NOTDETECTED", - 510 => "NOTDETECTED", - 511 => "NOTDETECTED", - 512 => "NOTDETECTED", - 513 => "NOTDETECTED", - 514 => "NOTDETECTED", - 515 => "NOTDETECTED", - 516 => "NOTDETECTED", - 517 => "NOTDETECTED", - 518 => "NOTDETECTED", - 519 => "NOTDETECTED", - 520 => "NOTDETECTED", - 521 => "NOTDETECTED", - 522 => "NOTDETECTED", - 523 => "NOTDETECTED", - 603 => "DETECTED", # dual frequency (similar to single freq with varying amplitude), mode [1] AVMD_DETECT_FREQ - 604 => "DETECTED", - 605 => "DETECTED", - 606 => "DETECTED", - 607 => "DETECTED", - 608 => "DETECTED", - 609 => "DETECTED", - 610 => "DETECTED", - 611 => "DETECTED", - 612 => "DETECTED", - 613 => "DETECTED", - 614 => "DETECTED", - 615 => "DETECTED", - 616 => "DETECTED", - 617 => "DETECTED", - 618 => "DETECTED", - 619 => "DETECTED", - 620 => "DETECTED", - 621 => "DETECTED", - 622 => "DETECTED", - 623 => "DETECTED", - 703 => "NOTDETECTED", # dual frequency (similar to single freq with varying amplitude), mode [2] AVMD_DETECT_BOTH - 704 => "NOTDETECTED", - 705 => "NOTDETECTED", - 706 => "NOTDETECTED", - 707 => "NOTDETECTED", - 708 => "NOTDETECTED", - 709 => "NOTDETECTED", - 710 => "NOTDETECTED", - 711 => "NOTDETECTED", - 712 => "NOTDETECTED", - 713 => "NOTDETECTED", - 714 => "NOTDETECTED", - 715 => "NOTDETECTED", - 716 => "NOTDETECTED", - 717 => "NOTDETECTED", - 718 => "NOTDETECTED", - 719 => "NOTDETECTED", - 720 => "NOTDETECTED", - 721 => "NOTDETECTED", - 722 => "NOTDETECTED", - 723 => "NOTDETECTED", - 840531000 => "DETECTED", # obscure voicemails, mode AVMD_DETECT_BOTH - 840531001 => "DETECTED", - 840531002 => "DETECTED", - 840531003 => "DETECTED", - 840531004 => "DETECTED", - 840531005 => "DETECTED", - 840531006 => "DETECTED", - 840531007 => "DETECTED", - 840531008 => "DETECTED", - 840531009 => "DETECTED", - 840531010 => "DETECTED", - 840531011 => "DETECTED", - 840531012 => "DETECTED", - 840531013 => "DETECTED", - 840531014 => "DETECTED", - 840531200 => "DETECTED", # obscure voicemails, mode AVMD_DETECT_FREQ - 840531201 => "DETECTED", - 840531202 => "DETECTED", - 840531203 => "DETECTED", - 840531204 => "DETECTED", - 840531205 => "DETECTED", - 840531206 => "DETECTED", - 840531207 => "DETECTED", - 840531208 => "DETECTED", - 840531209 => "DETECTED", - 840531210 => "DETECTED", - 840531211 => "DETECTED", - 840531212 => "DETECTED", - 840531213 => "DETECTED", - 840531214 => "DETECTED", - 840531400 => "DETECTED", # obscure voicemails ATT pack - 840531401 => "DETECTED", - 840531402 => "DETECTED", - 840531403 => "DETECTED", - 840531404 => "DETECTED", - 840531405 => "DETECTED", - 840531051 => "NOTDETECTED", # fragment of "Save tonight" by Eagle-Eye Cherry covered by D-Lete-Funk-K + 503 => "NOTDETECTED", # dual frequency (similar to single freq with varying amplitude), mode [0] AVMD_DETECT_AMP + 504 => "NOTDETECTED", + 505 => "NOTDETECTED", + 506 => "NOTDETECTED", + 507 => "NOTDETECTED", + 508 => "NOTDETECTED", + 509 => "NOTDETECTED", + 510 => "NOTDETECTED", + 511 => "NOTDETECTED", + 512 => "NOTDETECTED", + 513 => "NOTDETECTED", + 514 => "NOTDETECTED", + 515 => "NOTDETECTED", + 516 => "NOTDETECTED", + 517 => "NOTDETECTED", + 518 => "NOTDETECTED", + 519 => "NOTDETECTED", + 520 => "NOTDETECTED", + 521 => "NOTDETECTED", + 522 => "NOTDETECTED", + 523 => "NOTDETECTED", + 603 => "DETECTED", # dual frequency (similar to single freq with varying amplitude), mode [1] AVMD_DETECT_FREQ + 604 => "DETECTED", + 605 => "DETECTED", + 606 => "DETECTED", + 607 => "DETECTED", + 608 => "DETECTED", + 609 => "DETECTED", + 610 => "DETECTED", + 611 => "DETECTED", + 612 => "DETECTED", + 613 => "DETECTED", + 614 => "DETECTED", + 615 => "DETECTED", + 616 => "DETECTED", + 617 => "DETECTED", + 618 => "DETECTED", + 619 => "DETECTED", + 620 => "DETECTED", + 621 => "DETECTED", + 622 => "DETECTED", + 623 => "DETECTED", + 703 => "NOTDETECTED", # dual frequency (similar to single freq with varying amplitude), mode [2] AVMD_DETECT_BOTH + 704 => "NOTDETECTED", + 705 => "NOTDETECTED", + 706 => "NOTDETECTED", + 707 => "NOTDETECTED", + 708 => "NOTDETECTED", + 709 => "NOTDETECTED", + 710 => "NOTDETECTED", + 711 => "NOTDETECTED", + 712 => "NOTDETECTED", + 713 => "NOTDETECTED", + 714 => "NOTDETECTED", + 715 => "NOTDETECTED", + 716 => "NOTDETECTED", + 717 => "NOTDETECTED", + 718 => "NOTDETECTED", + 719 => "NOTDETECTED", + 720 => "NOTDETECTED", + 721 => "NOTDETECTED", + 722 => "NOTDETECTED", + 723 => "NOTDETECTED", + 840531000 => "DETECTED", # obscure voicemails, mode AVMD_DETECT_BOTH + 840531001 => "DETECTED", + 840531002 => "DETECTED", + 840531003 => "DETECTED", + 840531004 => "DETECTED", + 840531005 => "DETECTED", + 840531006 => "DETECTED", + 840531007 => "DETECTED", + 840531008 => "DETECTED", + 840531009 => "DETECTED", + 840531010 => "DETECTED", + 840531011 => "DETECTED", + 840531012 => "DETECTED", + 840531013 => "DETECTED", + 840531014 => "DETECTED", + 840531200 => "DETECTED", # obscure voicemails, mode AVMD_DETECT_FREQ + 840531201 => "DETECTED", + 840531202 => "DETECTED", + 840531203 => "DETECTED", + 840531204 => "DETECTED", + 840531205 => "DETECTED", + 840531206 => "DETECTED", + 840531207 => "DETECTED", + 840531208 => "DETECTED", + 840531209 => "DETECTED", + 840531210 => "DETECTED", + 840531211 => "DETECTED", + 840531212 => "DETECTED", + 840531213 => "DETECTED", + 840531214 => "DETECTED", + 840531400 => "DETECTED", # obscure voicemails ATT pack + 840531401 => "DETECTED", + 840531402 => "DETECTED", + 840531403 => "DETECTED", + 840531404 => "DETECTED", + 840531405 => "DETECTED", + 840531051 => "NOTDETECTED", # fragment of "Save tonight" by Eagle-Eye Cherry covered by D-Lete-Funk-K ); my $host = "127.0.0.1"; @@ -140,24 +140,24 @@ my $hanguped = 0; if ($#ARGV + 1 eq 1) { - $callerid = $ARGV[0]; - print "\nDialing as [" .$callerid ."]\n"; + $callerid = $ARGV[0]; + print "\nDialing as [" .$callerid ."]\n"; } elsif ($#ARGV + 1 > 1) { - die "Please specify single caller id.\n"; + die "Please specify single caller id.\n"; } else { - die "Please specify caller id.\n"; + die "Please specify caller id.\n"; } print "Connecting...\t"; my $con = new ESL::ESLconnection($host, $port, $pass); if (!$con) { - die "Unable to establish connection to $host:$port\n"; + die "Unable to establish connection to $host:$port\n"; } if ($con->connected()) { - print "OK.\n"; + print "OK.\n"; } else { - die "Connection failure.\n"; + die "Connection failure.\n"; } print "Subscribing to avmd events...\t"; @@ -171,95 +171,95 @@ printf("\nRunning [" .keys(%numbers) ."] tests.\n\n"); printf("outbound uuid | destination number | timestamp | expectation | test result | freq | f-variance | amplitude | a-variance | resolution | offset | idx\n\n"); foreach $dest (sort keys %numbers) { - if (!$con->connected()) { - last; - } - $expectation = $numbers{$dest}; - test_once($dest, $callerid, $expectation); + if (!$con->connected()) { + last; + } + $expectation = $numbers{$dest}; + test_once($dest, $callerid, $expectation); } print "Disconnected.\n\n"; if (($failed == 0) && ($hanguped == 0)) { - printf("\n\nOK. All PASS [%s]\n\n", $passed); + printf("\n\nOK. All PASS [%s]\n\n", $passed); } else { - printf("PASS [%s], FAIL [%s], HANGUP [%s]\n\n", $passed, $failed, $hanguped); + printf("PASS [%s], FAIL [%s], HANGUP [%s]\n\n", $passed, $failed, $hanguped); } sub test_once { - my ($dest, $callerid, $expectation) = @_; - my $originate_string = - 'originate ' . - '{ignore_early_media=true,' . - 'origination_uuid=%s,' . - 'originate_timeout=60,' . - 'origination_caller_id_number=' . $callerid . ',' . - 'origination_caller_id_name=' . $callerid . '}'; - my $outcome = ""; - my $result = ""; - my $event_uuid = "N/A"; - my $uuid_in = ""; - my $freq = "N/A"; - my $freq_var = "N/A"; - my $amp = "N/A"; - my $amp_var = "N/A"; - my $resolution = "N/A"; - my $offset = "N/A"; - my $idx = "N/A"; + my ($dest, $callerid, $expectation) = @_; + my $originate_string = + 'originate ' . + '{ignore_early_media=true,' . + 'origination_uuid=%s,' . + 'originate_timeout=60,' . + 'origination_caller_id_number=' . $callerid . ',' . + 'origination_caller_id_name=' . $callerid . '}'; + my $outcome = ""; + my $result = ""; + my $event_uuid = "N/A"; + my $uuid_in = ""; + my $freq = "N/A"; + my $freq_var = "N/A"; + my $amp = "N/A"; + my $amp_var = "N/A"; + my $resolution = "N/A"; + my $offset = "N/A"; + my $idx = "N/A"; - if(defined($endpoint)) { - $originate_string .= $endpoint; - } else { - $originate_string .= 'loopback/' . $dest . '/' . $context; - } - $originate_string .= ' ' . '&playback(' . $playback . ')'; + if(defined($endpoint)) { + $originate_string .= $endpoint; + } else { + $originate_string .= 'loopback/' . $dest . '/' . $context; + } + $originate_string .= ' ' . '&playback(' . $playback . ')'; - my $uuid_out = $con->api('create_uuid')->getBody(); - my ($time_epoch, $time_hires) = Time::HiRes::gettimeofday(); + my $uuid_out = $con->api('create_uuid')->getBody(); + my ($time_epoch, $time_hires) = Time::HiRes::gettimeofday(); - printf("[%s] [%s]", $uuid_out, $dest); - $con->bgapi(sprintf($originate_string, $uuid_out)); + printf("[%s] [%s]", $uuid_out, $dest); + $con->bgapi(sprintf($originate_string, $uuid_out)); - while($con->connected()) { - my $e = $con->recvEvent(); - if ($e) { - my $event_name = $e->getHeader("Event-Name"); - if ($event_name eq 'CUSTOM') { - my $avmd_event_type = $e->getHeader("Event-Subclass"); - if ($avmd_event_type eq 'avmd::start') { - $uuid_in = $e->getHeader("Unique-ID"); - } elsif (!($uuid_in eq "") && (($avmd_event_type eq 'avmd::beep') || ($avmd_event_type eq 'avmd::stop'))) { - $event_uuid = $e->getHeader("Unique-ID"); - if ($event_uuid eq $uuid_in) { - if ($avmd_event_type eq 'avmd::beep') { - $freq = $e->getHeader("Frequency"); - $freq_var = $e->getHeader("Frequency-variance"); - $amp = $e->getHeader("Amplitude"); - $amp_var = $e->getHeader("Amplitude-variance"); - $resolution = $e->getHeader("Detector-resolution"); - $offset = $e->getHeader("Detector-offset"); - $idx = $e->getHeader("Detector-index"); - } - $outcome = $e->getHeader("Beep-Status"); - if ($outcome eq $expectation) { - $result = "PASS"; - $passed++; - } else { - $result = "FAIL"; - $failed++; - } - last; - } - } - } elsif ($event_name eq 'CHANNEL_HANGUP') { - $event_uuid = $e->getHeader("variable_origination_uuid"); - if ((defined $event_uuid) && ($event_uuid eq $uuid_out)) { - $outcome = "HANGUP"; - $result = "HANGUP"; - $hanguped++; - last; - } - } - } - } - printf("\t[%s]\t[%s]\t\t[%s]\t[%s]HZ\t[%s]\t[%s]\t[%s]\t[%s][%s][%s]\n", POSIX::strftime('%Y-%m-%d %H:%M:%S', localtime($time_epoch)), $expectation, $result, $freq, $freq_var, $amp, $amp_var, $resolution, $offset, $idx); - Time::HiRes::sleep(0.5); # avoid switch_core_session.c:2265 Throttle Error! 33, switch_time.c:1227 Over Session Rate of 30! + while($con->connected()) { + my $e = $con->recvEvent(); + if ($e) { + my $event_name = $e->getHeader("Event-Name"); + if ($event_name eq 'CUSTOM') { + my $avmd_event_type = $e->getHeader("Event-Subclass"); + if ($avmd_event_type eq 'avmd::start') { + $uuid_in = $e->getHeader("Unique-ID"); + } elsif (!($uuid_in eq "") && (($avmd_event_type eq 'avmd::beep') || ($avmd_event_type eq 'avmd::stop'))) { + $event_uuid = $e->getHeader("Unique-ID"); + if ($event_uuid eq $uuid_in) { + if ($avmd_event_type eq 'avmd::beep') { + $freq = $e->getHeader("Frequency"); + $freq_var = $e->getHeader("Frequency-variance"); + $amp = $e->getHeader("Amplitude"); + $amp_var = $e->getHeader("Amplitude-variance"); + $resolution = $e->getHeader("Detector-resolution"); + $offset = $e->getHeader("Detector-offset"); + $idx = $e->getHeader("Detector-index"); + } + $outcome = $e->getHeader("Beep-Status"); + if ($outcome eq $expectation) { + $result = "PASS"; + $passed++; + } else { + $result = "FAIL"; + $failed++; + } + last; + } + } + } elsif ($event_name eq 'CHANNEL_HANGUP') { + $event_uuid = $e->getHeader("variable_origination_uuid"); + if ((defined $event_uuid) && ($event_uuid eq $uuid_out)) { + $outcome = "HANGUP"; + $result = "HANGUP"; + $hanguped++; + last; + } + } + } + } + printf("\t[%s]\t[%s]\t\t[%s]\t[%s]HZ\t[%s]\t[%s]\t[%s]\t[%s][%s][%s]\n", POSIX::strftime('%Y-%m-%d %H:%M:%S', localtime($time_epoch)), $expectation, $result, $freq, $freq_var, $amp, $amp_var, $resolution, $offset, $idx); + Time::HiRes::sleep(0.5); # avoid switch_core_session.c:2265 Throttle Error! 33, switch_time.c:1227 Over Session Rate of 30! } diff --git a/src/mod/applications/mod_commands/mod_commands.c b/src/mod/applications/mod_commands/mod_commands.c index ad5bd51ce9..a86cea3538 100644 --- a/src/mod/applications/mod_commands/mod_commands.c +++ b/src/mod/applications/mod_commands/mod_commands.c @@ -967,6 +967,10 @@ SWITCH_STANDARD_API(timer_test_function) stream->write_function(stream, "Avg: %0.3fms Total Time: %0.3fms\n", (float) ((float) (total / (x - 1)) / 1000), (float) ((float) (end - start) / 1000)); + if (switch_core_timer_destroy(&timer) != SWITCH_STATUS_SUCCESS) { + stream->write_function(stream, "Timer Destroy Error!\n"); + } + end: switch_core_destroy_memory_pool(&pool); @@ -2417,7 +2421,7 @@ SWITCH_STANDARD_API(uptime_function) return SWITCH_STATUS_SUCCESS; } -#define CTL_SYNTAX "[recover|send_sighup|hupall|pause [inbound|outbound]|resume [inbound|outbound]|shutdown [cancel|elegant|asap|now|restart]|sps|sps_peak_reset|sync_clock|sync_clock_when_idle|reclaim_mem|max_sessions|min_dtmf_duration [num]|max_dtmf_duration [num]|default_dtmf_duration [num]|min_idle_cpu|loglevel [level]|debug_level [level]]" +#define CTL_SYNTAX "[recover|send_sighup|hupall|pause [inbound|outbound]|resume [inbound|outbound]|shutdown [cancel|elegant|asap|now|restart]|sps|sps_peak_reset|sync_clock|sync_clock_when_idle|reclaim_mem|max_sessions|min_dtmf_duration [num]|max_dtmf_duration [num]|default_dtmf_duration [num]|min_idle_cpu|loglevel [level]|debug_level [level]|mdns_resolve [enable|disable]]" SWITCH_STANDARD_API(ctl_function) { int argc; @@ -2673,6 +2677,25 @@ SWITCH_STANDARD_API(ctl_function) } else { stream->write_function(stream, "+OK clock will synchronize when there are no more calls\n"); } + } else if (!strcasecmp(argv[0], "mdns_resolve")) { + switch_bool_t set = 0; + if (argv[1]) { + if (!strcasecmp(argv[1], "enable")) { + arg = 1; + set = 1; + } else if (!strcasecmp(argv[1], "disable")) { + arg = 0; + set = 1; + } + } + if (set) { + switch_core_session_ctl(SCSC_MDNS_RESOLVE, &arg); + stream->write_function(stream, "+OK\n"); + arg = 0; + } else { + stream->write_function(stream, "-ERR Invalid command\nUSAGE: fsctl %s\n", CTL_SYNTAX); + goto end; + } } else { stream->write_function(stream, "-ERR Invalid command\nUSAGE: fsctl %s\n", CTL_SYNTAX); goto end; @@ -4022,6 +4045,46 @@ SWITCH_STANDARD_API(uuid_display_function) return SWITCH_STATUS_SUCCESS; } +#define MEDIA_PARAMS_SYNTAX " " +SWITCH_STANDARD_API(uuid_media_params_function) +{ + char *mycmd = NULL, *argv[2] = { 0 }; + int argc = 0; + switch_status_t status = SWITCH_STATUS_FALSE; + switch_core_session_t *tsession = NULL; + + if (!zstr(cmd) && (mycmd = strdup(cmd))) { + argc = switch_separate_string(mycmd, ' ', argv, (sizeof(argv) / sizeof(argv[0]))); + } + + if (zstr(cmd) || argc < 2 || zstr(argv[0]) || zstr(argv[1])) { + stream->write_function(stream, "-USAGE: %s\n", MEDIA_PARAMS_SYNTAX); + goto end; + } else { + if ((tsession = switch_core_session_locate(argv[0]))) { + switch_channel_t *channel = switch_core_session_get_channel(session); + + if (switch_false(argv[1])) { + switch_channel_clear_flag(channel, CF_MANUAL_MEDIA_PARAMS); + } else if ((status = switch_core_media_media_params(tsession, argv[1])) == SWITCH_STATUS_SUCCESS) { + switch_channel_set_flag(channel, CF_MANUAL_MEDIA_PARAMS); + } + switch_core_session_rwunlock(tsession); + } + } + + if (status == SWITCH_STATUS_SUCCESS) { + stream->write_function(stream, "+OK Success\n"); + } else { + stream->write_function(stream, "-ERR Operation failed\n"); + } + + end: + + switch_safe_free(mycmd); + return SWITCH_STATUS_SUCCESS; +} + #define BUGLIST_SYNTAX "" SWITCH_STANDARD_API(uuid_buglist_function) { @@ -4722,6 +4785,18 @@ SWITCH_STANDARD_API(session_record_function) } else { stream->write_function(stream, "+OK Success\n"); } + } else if (!strcasecmp(action, "pause")) { + if (switch_ivr_record_session_pause(rsession, path, SWITCH_TRUE) != SWITCH_STATUS_SUCCESS) { + stream->write_function(stream, "-ERR Cannot pause recording session!\n"); + } else { + stream->write_function(stream, "+OK Success\n"); + } + } else if (!strcasecmp(action, "resume")) { + if (switch_ivr_record_session_pause(rsession, path, SWITCH_FALSE) != SWITCH_STATUS_SUCCESS) { + stream->write_function(stream, "-ERR Cannot resume recording session!\n"); + } else { + stream->write_function(stream, "+OK Success\n"); + } } else if (!strcasecmp(action, "mask")) { if (switch_ivr_record_session_mask(rsession, path, SWITCH_TRUE) != SWITCH_STATUS_SUCCESS) { stream->write_function(stream, "-ERR Cannot mask recording session!\n"); @@ -6667,7 +6742,7 @@ SWITCH_STANDARD_API(xml_flush_function) argc = switch_split(mycmd, ' ', argv); } - if (argc == 3) { + if (argc > 1) { r = switch_xml_clear_user_cache(argv[0], argv[1], argv[2]); } else { r = switch_xml_clear_user_cache(NULL, NULL, NULL); @@ -7485,6 +7560,18 @@ SWITCH_STANDARD_API(json_function) return SWITCH_STATUS_SUCCESS; } +SWITCH_STANDARD_API(memory_function) +{ + const char *err; + if (!(err = switch_memory_usage_stream(stream))) { + stream->write_function(stream, "+OK\n"); + } else { + stream->write_function(stream, "-ERR %s\n", err); + } + + return SWITCH_STATUS_SUCCESS; +} + SWITCH_MODULE_LOAD_FUNCTION(mod_commands_load) { switch_api_interface_t *commands_api_interface; @@ -7605,6 +7692,7 @@ SWITCH_MODULE_LOAD_FUNCTION(mod_commands_load) SWITCH_ADD_API(commands_api_interface, "uuid_deflect", "Send a deflect", uuid_deflect, UUID_DEFLECT_SYNTAX); SWITCH_ADD_API(commands_api_interface, "uuid_displace", "Displace audio", session_displace_function, " [start|stop] [] [mux]"); SWITCH_ADD_API(commands_api_interface, "uuid_display", "Update phone display", uuid_display_function, DISPLAY_SYNTAX); + SWITCH_ADD_API(commands_api_interface, "uuid_media_params", "Update remote vid params", uuid_media_params_function, MEDIA_PARAMS_SYNTAX); SWITCH_ADD_API(commands_api_interface, "uuid_drop_dtmf", "Drop all DTMF or replace it with a mask", uuid_drop_dtmf, UUID_DROP_DTMF_SYNTAX); SWITCH_ADD_API(commands_api_interface, "uuid_dump", "Dump session vars", uuid_dump_function, DUMP_SYNTAX); SWITCH_ADD_API(commands_api_interface, "uuid_exists", "Check if a uuid exists", uuid_exists_function, EXISTS_SYNTAX); @@ -7652,6 +7740,7 @@ SWITCH_MODULE_LOAD_FUNCTION(mod_commands_load) SWITCH_ADD_API(commands_api_interface, "file_exists", "Check if a file exists on server", file_exists_function, ""); SWITCH_ADD_API(commands_api_interface, "getcputime", "Gets CPU time in milliseconds (user,kernel)", getcputime_function, GETCPUTIME_SYNTAX); SWITCH_ADD_API(commands_api_interface, "json", "JSON API", json_function, "JSON"); + SWITCH_ADD_API(commands_api_interface, "memory", "Memory usage statistics", memory_function, "memory"); SWITCH_ADD_JSON_API(json_api_interface, "mediaStats", "JSON Media Stats", json_stats_function, ""); @@ -7720,6 +7809,8 @@ SWITCH_MODULE_LOAD_FUNCTION(mod_commands_load) switch_console_set_complete("add fsctl flush_db_handles"); switch_console_set_complete("add fsctl min_idle_cpu"); switch_console_set_complete("add fsctl send_sighup"); + switch_console_set_complete("add fsctl mdns_resolve disable"); + switch_console_set_complete("add fsctl mdns_resolve enable"); switch_console_set_complete("add interface_ip auto ::console::list_interfaces"); switch_console_set_complete("add interface_ip ipv4 ::console::list_interfaces"); switch_console_set_complete("add interface_ip ipv6 ::console::list_interfaces"); @@ -7793,6 +7884,7 @@ SWITCH_MODULE_LOAD_FUNCTION(mod_commands_load) switch_console_set_complete("add uuid_deflect ::console::list_uuid"); switch_console_set_complete("add uuid_displace ::console::list_uuid"); switch_console_set_complete("add uuid_display ::console::list_uuid"); + switch_console_set_complete("add uuid_media_params ::console::list_uuid"); switch_console_set_complete("add uuid_drop_dtmf ::console::list_uuid"); switch_console_set_complete("add uuid_dump ::console::list_uuid"); switch_console_set_complete("add uuid_answer ::console::list_uuid"); @@ -7804,6 +7896,8 @@ SWITCH_MODULE_LOAD_FUNCTION(mod_commands_load) switch_console_set_complete("add uuid_flush_dtmf ::console::list_uuid"); switch_console_set_complete("add uuid_getvar ::console::list_uuid"); switch_console_set_complete("add uuid_hold ::console::list_uuid"); + switch_console_set_complete("add uuid_hold off ::console::list_uuid"); + switch_console_set_complete("add uuid_hold toggle ::console::list_uuid"); switch_console_set_complete("add uuid_send_info ::console::list_uuid"); switch_console_set_complete("add uuid_jitterbuffer ::console::list_uuid"); switch_console_set_complete("add uuid_kill ::console::list_uuid"); diff --git a/src/mod/applications/mod_conference/conference_api.c b/src/mod/applications/mod_conference/conference_api.c index ee74f2a371..bd24484928 100644 --- a/src/mod/applications/mod_conference/conference_api.c +++ b/src/mod/applications/mod_conference/conference_api.c @@ -89,6 +89,8 @@ api_command_t conference_api_sub_commands[] = { {"undeaf", (void_fn_t) & conference_api_sub_undeaf, CONF_API_SUB_MEMBER_TARGET, "undeaf", "<[member_id|all]|last|non_moderator>"}, {"vid-filter", (void_fn_t) & conference_api_sub_video_filter, CONF_API_SUB_MEMBER_TARGET, "vid-filter", "<[member_id|all]|last|non_moderator> "}, {"relate", (void_fn_t) & conference_api_sub_relate, CONF_API_SUB_ARGS_SPLIT, "relate", "[,] [,] [nospeak|nohear|clear]"}, + {"getvar", (void_fn_t) & conference_api_sub_getvar, CONF_API_SUB_ARGS_SPLIT, "getvar", ""}, + {"setvar", (void_fn_t) & conference_api_sub_setvar, CONF_API_SUB_ARGS_SPLIT, "setvar", " "}, {"lock", (void_fn_t) & conference_api_sub_lock, CONF_API_SUB_ARGS_SPLIT, "lock", ""}, {"unlock", (void_fn_t) & conference_api_sub_unlock, CONF_API_SUB_ARGS_SPLIT, "unlock", ""}, {"dial", (void_fn_t) & conference_api_sub_dial, CONF_API_SUB_ARGS_SPLIT, "dial", "/ "}, @@ -138,17 +140,17 @@ switch_status_t conference_api_sub_pause_play(conference_obj_t *conference, swit } if (argc == 3) { - uint32_t id = atoi(argv[2]); + const char * id = argv[2]; conference_member_t *member; - if ((member = conference_member_get(conference, id))) { + if ((member = conference_member_get_by_str(conference, id))) { switch_mutex_lock(member->fnode_mutex); conference_fnode_toggle_pause(member->fnode, stream); switch_mutex_unlock(member->fnode_mutex); switch_thread_rwlock_unlock(member->rwlock); return SWITCH_STATUS_SUCCESS; } else { - stream->write_function(stream, "-ERR Member: %u not found.\n", id); + stream->write_function(stream, "-ERR Member: %s not found.\n", id); } } @@ -166,17 +168,17 @@ switch_status_t conference_api_sub_play_status(conference_obj_t *conference, swi } if (argc == 3) { - uint32_t id = atoi(argv[2]); + const char *id = argv[2]; conference_member_t *member; - if ((member = conference_member_get(conference, id))) { + if ((member = conference_member_get_by_str(conference, id))) { switch_mutex_lock(member->fnode_mutex); conference_fnode_check_status(member->fnode, stream); switch_mutex_unlock(member->fnode_mutex); switch_thread_rwlock_unlock(member->rwlock); return SWITCH_STATUS_SUCCESS; } else { - stream->write_function(stream, "-ERR Member: %u not found.\n", id); + stream->write_function(stream, "-ERR Member: %s not found.\n", id); } } @@ -2518,7 +2520,6 @@ static void clear_role_id(conference_obj_t *conference, conference_member_t *mem switch_status_t conference_api_sub_vid_res_id(conference_obj_t *conference, switch_stream_handle_t *stream, int argc, char **argv) { uint8_t all = 0, clear = 0, force = 0; - uint32_t member_id; char *res_id = NULL; conference_member_t *member; @@ -2538,7 +2539,7 @@ switch_status_t conference_api_sub_vid_res_id(conference_obj_t *conference, swit if (argc > 4) force = strcasecmp(argv[4], "force") ? 0 : 1; - if (!(member_id = atoi(argv[2]))) { + if (!atoi(argv[2])) { all = strcasecmp(argv[2], "all") ? 0 : 1; } @@ -2550,13 +2551,11 @@ switch_status_t conference_api_sub_vid_res_id(conference_obj_t *conference, swit } } switch_mutex_unlock(conference->member_mutex); - } else if (member_id) { - if (!(member = conference_member_get(conference, member_id))) + } else { + if (!(member = conference_member_get_by_str(conference, argv[2]))) return SWITCH_STATUS_GENERR; conference_api_sub_vid_res_id_member(member, stream, res_id, clear, force); switch_thread_rwlock_unlock(member->rwlock); - } else { - return SWITCH_STATUS_GENERR; } return SWITCH_STATUS_SUCCESS; @@ -2735,10 +2734,10 @@ switch_status_t conference_api_sub_file_seek(conference_obj_t *conference, switc } if (argc == 4) { - uint32_t id = atoi(argv[3]); - conference_member_t *member = conference_member_get(conference, id); + const char *id = argv[3]; + conference_member_t *member = conference_member_get_by_str(conference, id); if (member == NULL) { - stream->write_function(stream, "-ERR Member: %u not found.\n", id); + stream->write_function(stream, "-ERR Member: %s not found.\n", id); return SWITCH_STATUS_GENERR; } @@ -2833,7 +2832,7 @@ switch_status_t conference_api_sub_play(conference_obj_t *conference, switch_str } ret_status = SWITCH_STATUS_SUCCESS; } else if (argc >= 4) { - uint32_t id = atoi(argv[3]); + const char *id = argv[3]; conference_member_t *member; switch_bool_t mux = SWITCH_TRUE; @@ -2841,9 +2840,9 @@ switch_status_t conference_api_sub_play(conference_obj_t *conference, switch_str mux = SWITCH_FALSE; } - if ((member = conference_member_get(conference, id))) { + if ((member = conference_member_get_by_str(conference, id))) { if (conference_member_play_file(member, argv[2], 0, mux) == SWITCH_STATUS_SUCCESS) { - stream->write_function(stream, "+OK (play) Playing file %s to member %u\n", argv[2], id); + stream->write_function(stream, "+OK (play) Playing file %s to member %u\n", argv[2], member->id); if (test_eflag(conference, EFLAG_PLAY_FILE_MEMBER) && switch_event_create_subclass(&event, SWITCH_EVENT_CUSTOM, CONF_EVENT_MAINT) == SWITCH_STATUS_SUCCESS) { conference_member_add_event_data(member, event); @@ -2899,7 +2898,7 @@ switch_status_t conference_api_sub_saymember(conference_obj_t *conference, switc char *expanded = NULL; char *start_text = NULL; char *workspace = NULL; - uint32_t id = 0; + const char *id = NULL; conference_member_t *member = NULL; switch_event_t *event; @@ -2918,15 +2917,15 @@ switch_status_t conference_api_sub_saymember(conference_obj_t *conference, switc text = start_text; } - id = atoi(workspace); + id = workspace; if (!id || zstr(text)) { stream->write_function(stream, "-ERR (saymember) No Text!\n"); goto done; } - if (!(member = conference_member_get(conference, id))) { - stream->write_function(stream, "-ERR (saymember) Unknown Member %u!\n", id); + if (!(member = conference_member_get_by_str(conference, id))) { + stream->write_function(stream, "-ERR (saymember) Unknown Member %s!\n", id); goto done; } @@ -3236,15 +3235,15 @@ switch_status_t conference_api_sub_stop(conference_obj_t *conference, switch_str return SWITCH_STATUS_GENERR; if (argc == 4) { - uint32_t id = atoi(argv[3]); + const char *id = argv[3]; conference_member_t *member; - if ((member = conference_member_get(conference, id))) { + if ((member = conference_member_get_by_str(conference, id))) { uint32_t stopped = conference_member_stop_file(member, async ? FILE_STOP_ASYNC : current ? FILE_STOP_CURRENT : FILE_STOP_ALL); stream->write_function(stream, "+OK Stopped %u files.\n", stopped); switch_thread_rwlock_unlock(member->rwlock); } else { - stream->write_function(stream, "-ERR Member: %u not found.\n", id); + stream->write_function(stream, "-ERR Member: %s not found.\n", id); } } else { uint32_t stopped = conference_file_stop(conference, async ? FILE_STOP_ASYNC : current ? FILE_STOP_CURRENT : FILE_STOP_ALL); @@ -3436,6 +3435,30 @@ switch_status_t conference_api_sub_relate(conference_obj_t *conference, switch_s return SWITCH_STATUS_SUCCESS; } +switch_status_t conference_api_sub_getvar(conference_obj_t *conference, switch_stream_handle_t *stream, int argc, char **argv) +{ + const char *val = NULL; + const char *var = argv[2]; + + if (var) val = conference_get_variable(conference, var); + + stream_write(stream, "%s", switch_str_nil(val)); + + return SWITCH_STATUS_SUCCESS; +} + +switch_status_t conference_api_sub_setvar(conference_obj_t *conference, switch_stream_handle_t *stream, int argc, char **argv) +{ + const char *val = argv[3]; + const char *var = argv[2]; + + if (var) conference_set_variable(conference, var, val); + + stream_write(stream, "+OK\n", VA_NONE); + + return SWITCH_STATUS_SUCCESS; +} + switch_status_t conference_api_sub_lock(conference_obj_t *conference, switch_stream_handle_t *stream, int argc, char **argv) { switch_event_t *event; @@ -3659,13 +3682,13 @@ switch_status_t conference_api_sub_transfer(conference_obj_t *conference, switch for (x = 3; x < argc; x++) { conference_member_t *member = NULL; - uint32_t id = atoi(argv[x]); + const char *id = argv[x]; switch_channel_t *channel; switch_event_t *event; char *xdest = NULL; - if (!id || !(member = conference_member_get(conference, id))) { - stream->write_function(stream, "-ERR No Member %u in conference %s.\n", id, conference->name); + if (!id || !(member = conference_member_get_by_str(conference, id))) { + stream->write_function(stream, "-ERR No Member %s in conference %s.\n", id, conference->name); continue; } diff --git a/src/mod/applications/mod_conference/conference_event.c b/src/mod/applications/mod_conference/conference_event.c index 806dfc95ed..23adb127a8 100644 --- a/src/mod/applications/mod_conference/conference_event.c +++ b/src/mod/applications/mod_conference/conference_event.c @@ -634,7 +634,7 @@ void conference_event_adv_la(conference_obj_t *conference, conference_member_t * switch_channel_set_flag(member->channel, CF_VIDEO_REFRESH_REQ); switch_core_media_gen_key_frame(member->session); - if (conference && conference->la && member->session && !switch_channel_test_flag(member->channel, CF_VIDEO_ONLY)) { + if (conference && conference->la && member->session) { cJSON *msg, *data; const char *uuid = switch_core_session_get_uuid(member->session); const char *cookie = switch_channel_get_variable(member->channel, "event_channel_cookie"); diff --git a/src/mod/applications/mod_conference/conference_loop.c b/src/mod/applications/mod_conference/conference_loop.c index 5d284fab97..8c3804ef8c 100644 --- a/src/mod/applications/mod_conference/conference_loop.c +++ b/src/mod/applications/mod_conference/conference_loop.c @@ -839,6 +839,12 @@ void *SWITCH_THREAD_FUNC conference_loop_input(switch_thread_t *thread, void *ob continue; } + if (conference_utils_test_flag(member->conference, CFLAG_BREAKABLE) && + switch_channel_test_flag(channel, CF_BREAK)) { + switch_channel_clear_flag(channel, CF_BREAK); + break; + } + /* Read a frame. */ status = switch_core_session_read_frame(session, &read_frame, SWITCH_IO_FLAG_NONE, 0); diff --git a/src/mod/applications/mod_conference/conference_member.c b/src/mod/applications/mod_conference/conference_member.c index 4eebd7a37e..6df96fca97 100644 --- a/src/mod/applications/mod_conference/conference_member.c +++ b/src/mod/applications/mod_conference/conference_member.c @@ -186,7 +186,7 @@ void conference_member_update_status_field(conference_member_t *member) cJSON_AddItemToObject(video, "visible", cJSON_CreateFalse()); } - cJSON_AddItemToObject(video, "videoOnly", cJSON_CreateBool(switch_channel_test_flag(member->channel, CF_VIDEO_ONLY))); + cJSON_AddItemToObject(video, "noRecover", cJSON_CreateBool(switch_channel_test_flag(member->channel, CF_NO_RECOVER))); if (switch_true(switch_channel_get_variable_dup(member->channel, "video_screen_share", SWITCH_FALSE, -1))) { cJSON_AddItemToObject(video, "screenShare", cJSON_CreateTrue()); } @@ -442,6 +442,32 @@ conference_member_t *conference_member_get_by_var(conference_obj_t *conference, return member; } +/* traverse the conference member list for the specified member id or variable and return its pointer */ +conference_member_t *conference_member_get_by_str(conference_obj_t *conference, const char *id_str) +{ + conference_member_t *member = NULL; + + switch_assert(conference != NULL); + if (!id_str) { + return NULL; + } + if (strchr(id_str, '=')) { + char *var, *val; + + var = strdup(id_str); + switch_assert(var); + + if ((val = strchr(var, '='))) { + *val++ = '\0'; + } + member = conference_member_get_by_var(conference, var, val); + free(var); + } else { + member = conference_member_get(conference, atoi(id_str)); + } + return member; +} + /* traverse the conference member list for the specified member with role and return it's pointer */ conference_member_t *conference_member_get_by_role(conference_obj_t *conference, const char *role_id) @@ -1373,6 +1399,10 @@ void conference_member_send_all_dtmf(conference_member_t *member, conference_obj if (imember->id == member->id) { continue; } + if (conference_utils_member_test_flag(imember, MFLAG_SKIP_DTMF)) { + switch_log_printf(SWITCH_CHANNEL_LOG, SWITCH_LOG_DEBUG, "Skipping dist-dtmf to member due to skip-dtmf flag.\n"); + continue; + } if (imember->session) { const char *p; for (p = dtmf; p && *p; p++) { diff --git a/src/mod/applications/mod_conference/conference_utils.c b/src/mod/applications/mod_conference/conference_utils.c index 48716cc269..c8dd0fd4e9 100644 --- a/src/mod/applications/mod_conference/conference_utils.c +++ b/src/mod/applications/mod_conference/conference_utils.c @@ -124,6 +124,8 @@ void conference_utils_set_mflags(const char *flags, member_flag_t *f) f[MFLAG_MUTE_DETECT] = 1; } else if (!strcasecmp(argv[i], "dist-dtmf")) { f[MFLAG_DIST_DTMF] = 1; + } else if (!strcasecmp(argv[i], "skip-dtmf")) { + f[MFLAG_SKIP_DTMF] = 1; } else if (!strcasecmp(argv[i], "moderator")) { f[MFLAG_MOD] = 1; } else if (!strcasecmp(argv[i], "nomoh")) { @@ -216,6 +218,8 @@ void conference_utils_set_cflags(const char *flags, conference_flag_t *f) f[CFLAG_PERSONAL_CANVAS] = 1; } else if (!strcasecmp(argv[i], "ded-vid-layer-audio-floor")) { f[CFLAG_DED_VID_LAYER_AUDIO_FLOOR] = 1; + } else if (!strcasecmp(argv[i], "breakable")) { + f[CFLAG_BREAKABLE] = 1; } } diff --git a/src/mod/applications/mod_conference/conference_video.c b/src/mod/applications/mod_conference/conference_video.c index 357f30a560..e94b835c3d 100644 --- a/src/mod/applications/mod_conference/conference_video.c +++ b/src/mod/applications/mod_conference/conference_video.c @@ -3344,7 +3344,8 @@ void *SWITCH_THREAD_FUNC conference_video_muxing_thread_run(switch_thread_t *thr if (imember->watching_canvas_id == canvas->canvas_id && switch_channel_test_flag(imember->channel, CF_VIDEO_REFRESH_REQ)) { switch_channel_clear_flag(imember->channel, CF_VIDEO_REFRESH_REQ); - send_keyframe = SWITCH_TRUE; + canvas->send_keyframe = 30; + send_keyframe = 1; } if (conference_utils_test_flag(conference, CFLAG_MINIMIZE_VIDEO_ENCODING) && diff --git a/src/mod/applications/mod_conference/mod_conference.c b/src/mod/applications/mod_conference/mod_conference.c index 498de9fefc..ec1cd5c8f7 100644 --- a/src/mod/applications/mod_conference/mod_conference.c +++ b/src/mod/applications/mod_conference/mod_conference.c @@ -220,6 +220,7 @@ void *SWITCH_THREAD_FUNC conference_thread_run(switch_thread_t *thread, void *ob uint32_t x = 0; int32_t z = 0; conference_cdr_node_t *np; + switch_time_t last_heartbeat_time = switch_epoch_time_now(NULL); file_frame = switch_core_alloc(conference->pool, SWITCH_RECOMMENDED_BUFFER_SIZE); async_file_frame = switch_core_alloc(conference->pool, SWITCH_RECOMMENDED_BUFFER_SIZE); @@ -239,6 +240,7 @@ void *SWITCH_THREAD_FUNC conference_thread_run(switch_thread_t *thread, void *ob conference->record_count = 0; while (conference_globals.running && !conference_utils_test_flag(conference, CFLAG_DESTRUCT)) { + switch_time_t now = switch_epoch_time_now(NULL); switch_size_t file_sample_len = samples; switch_size_t file_data_len = samples * 2 * conference->channels; int has_file_data = 0, members_with_video = 0, members_with_avatar = 0, members_seeing_video = 0; @@ -257,6 +259,15 @@ void *SWITCH_THREAD_FUNC conference_thread_run(switch_thread_t *thread, void *ob floor_holder = conference->floor_holder; + if (conference->heartbeat_period_sec > 0 && (now - last_heartbeat_time) >= conference->heartbeat_period_sec) { + switch_event_t *heartbeat_event = NULL; + last_heartbeat_time = now; + switch_event_create_subclass(&heartbeat_event, SWITCH_EVENT_CUSTOM, CONF_EVENT_MAINT); + conference_event_add_data(conference, heartbeat_event); + switch_event_add_header_string(heartbeat_event, SWITCH_STACK_BOTTOM, "Action", "conference-heartbeat"); + switch_event_fire(&heartbeat_event); + } + for (imember = conference->members; imember; imember = imember->next) { if (!zstr(imember->text_framedata)) { switch_frame_t frame = { 0 }; @@ -1445,6 +1456,7 @@ void conference_jlist(conference_obj_t *conference, cJSON *json_conferences) ADDBOOL(json_conference_member_flags, "has_floor", member->id == member->conference->floor_holder); ADDBOOL(json_conference_member_flags, "is_moderator", conference_utils_member_test_flag(member, MFLAG_MOD)); ADDBOOL(json_conference_member_flags, "end_conference", conference_utils_member_test_flag(member, MFLAG_ENDCONF)); + ADDBOOL(json_conference_member_flags, "pass_digits", conference_utils_member_test_flag(member, MFLAG_DIST_DTMF)); } switch_mutex_unlock(conference->member_mutex); } @@ -2463,21 +2475,21 @@ SWITCH_STANDARD_APP(conference_function) switch_core_session_set_video_read_callback(session, conference_video_thread_callback, (void *)&member); switch_core_session_set_text_read_callback(session, conference_text_thread_callback, (void *)&member); - if (switch_channel_test_flag(channel, CF_VIDEO_ONLY) || !switch_channel_test_flag(channel, CF_AUDIO)) { - while(conference_utils_member_test_flag((&member), MFLAG_RUNNING) && switch_channel_ready(channel)) { - switch_frame_t *read_frame; - if (switch_channel_test_flag(channel, CF_AUDIO)) { - switch_core_session_read_frame(session, &read_frame, SWITCH_IO_FLAG_NONE, 0); - } - switch_yield(100000); - } - } else { - - /* Run the conference loop */ - do { + /* Run the conference loop */ + do { + switch_media_flow_t audio_flow = switch_core_session_media_flow(session, SWITCH_MEDIA_TYPE_AUDIO); + + if (switch_channel_test_flag(channel, CF_AUDIO) && (audio_flow == SWITCH_MEDIA_FLOW_SENDRECV || audio_flow == SWITCH_MEDIA_FLOW_RECVONLY)) { conference_loop_output(&member); - } while (member.loop_loop); - } + } else { + if (conference_utils_member_test_flag((&member), MFLAG_RUNNING) && switch_channel_ready(channel)) { + switch_yield(100000); + member.loop_loop = 1; + } else { + break; + } + } + } while (member.loop_loop); switch_core_session_video_reset(session); switch_channel_clear_flag_recursive(channel, CF_VIDEO_DECODED_READ); @@ -2644,24 +2656,44 @@ conference_obj_t *conference_find(char *name, char *domain) void conference_set_variable(conference_obj_t *conference, const char *var, const char *val) { + switch_assert(var); switch_mutex_lock(conference->flag_mutex); - switch_event_add_header_string(conference->variables, SWITCH_STACK_BOTTOM, var, val); + + if (!val) { + switch_event_del_header(conference->variables, var); + } else { + switch_event_add_header_string(conference->variables, SWITCH_STACK_BOTTOM, var, val); + } switch_mutex_unlock(conference->flag_mutex); } const char *conference_get_variable(conference_obj_t *conference, const char *var) { - const char *val; + const char *val = NULL, *rval = NULL; switch_mutex_lock(conference->flag_mutex); - val = switch_event_get_header(conference->variables, var); + if ((val = switch_event_get_header(conference->variables, var))) { + rval = switch_core_strdup(conference->pool, val); + } switch_mutex_unlock(conference->flag_mutex); - if (val) { - return switch_core_strdup(conference->pool, val); - } + return rval; +} - return NULL; +static void check_var_event(conference_obj_t *conference, switch_event_t *var_event) +{ + switch_event_header_t *hi = NULL; + + for (hi = var_event->headers; hi; hi = hi->next) { + char *vvar = hi->name; + char *vval = hi->value; + if (vvar && vval && !strncasecmp(vvar, "confvar_", 8)) { + vvar += 8; + if (vvar) { + conference_set_variable(conference, vvar, vval); + } + } + } } /* create a new conferene with a specific profile */ @@ -2767,6 +2799,8 @@ conference_obj_t *conference_new(char *name, conference_xml_cfg_t cfg, switch_co char *scale_h264_canvas_bandwidth = NULL; char *video_codec_config_profile_name = NULL; int tmp; + int heartbeat_period_sec = 0; + switch_event_t *var_event = NULL; /* Validate the conference name */ if (zstr(name)) { @@ -3130,6 +3164,8 @@ conference_obj_t *conference_new(char *name, conference_xml_cfg_t cfg, switch_co scale_h264_canvas_bandwidth = val; } else if (!strcasecmp(var, "video-codec-config-profile-name") && !zstr(val)) { video_codec_config_profile_name = val; + } else if (!strcasecmp(var, "heartbeat-period-sec") && !zstr(val)) { + heartbeat_period_sec = atoi(val); } } @@ -3649,6 +3685,10 @@ conference_obj_t *conference_new(char *name, conference_xml_cfg_t cfg, switch_co conference->verbose_events = 1; } + if (heartbeat_period_sec >= 20 || heartbeat_period_sec == 0) { + conference->heartbeat_period_sec = heartbeat_period_sec; + } + /* Create the conference unique identifier */ switch_uuid_get(&uuid); switch_uuid_format(uuid_str, &uuid); @@ -3666,6 +3706,14 @@ conference_obj_t *conference_new(char *name, conference_xml_cfg_t cfg, switch_co switch_mutex_init(&conference->member_mutex, SWITCH_MUTEX_NESTED, conference->pool); switch_mutex_init(&conference->canvas_mutex, SWITCH_MUTEX_NESTED, conference->pool); + switch_core_get_variables(&var_event); + check_var_event(conference, var_event); + switch_event_destroy(&var_event); + + switch_channel_get_variables(channel, &var_event); + check_var_event(conference, var_event); + switch_event_destroy(&var_event); + switch_mutex_lock(conference_globals.hash_mutex); conference_utils_set_flag(conference, CFLAG_INHASH); switch_core_hash_insert(conference_globals.conference_hash, conference->name, conference); diff --git a/src/mod/applications/mod_conference/mod_conference.h b/src/mod/applications/mod_conference/mod_conference.h index e551a4d053..f6f932fc07 100644 --- a/src/mod/applications/mod_conference/mod_conference.h +++ b/src/mod/applications/mod_conference/mod_conference.h @@ -214,6 +214,7 @@ typedef enum { MFLAG_VIDEO_JOIN, MFLAG_DED_VID_LAYER, MFLAG_HOLD, + MFLAG_SKIP_DTMF, /////////////////////////// MFLAG_MAX } member_flag_t; @@ -255,6 +256,7 @@ typedef enum { CFLAG_VIDEO_MUTE_EXIT_CANVAS, CFLAG_NO_MOH, CFLAG_DED_VID_LAYER_AUDIO_FLOOR, + CFLAG_BREAKABLE, ///////////////////////////////// CFLAG_MAX } conference_flag_t; @@ -760,6 +762,7 @@ typedef struct conference_obj { char *default_layout_name; int mux_paused; char *video_codec_config_profile_name; + int heartbeat_period_sec; } conference_obj_t; /* Relationship with another member */ @@ -1097,6 +1100,7 @@ void conference_member_set_score_iir(conference_member_t *member, uint32_t score conference_relationship_t *conference_member_add_relationship(conference_member_t *member, uint32_t id); conference_member_t *conference_member_get(conference_obj_t *conference, uint32_t id); +conference_member_t *conference_member_get_by_str(conference_obj_t *conference, const char *id_str); conference_member_t *conference_member_get_by_var(conference_obj_t *conference, const char *var, const char *val); conference_member_t *conference_member_get_by_role(conference_obj_t *conference, const char *role_id); switch_status_t conference_member_del_relationship(conference_member_t *member, uint32_t id); @@ -1214,6 +1218,8 @@ switch_status_t conference_api_sub_hold(conference_member_t *member, switch_stre switch_status_t conference_api_sub_unhold(conference_member_t *member, switch_stream_handle_t *stream, void *data); switch_status_t conference_api_sub_pauserec(conference_obj_t *conference, switch_stream_handle_t *stream, int argc, char **argv); switch_status_t conference_api_sub_volume_out(conference_member_t *member, switch_stream_handle_t *stream, void *data); +switch_status_t conference_api_sub_getvar(conference_obj_t *conference, switch_stream_handle_t *stream, int argc, char **argv); +switch_status_t conference_api_sub_setvar(conference_obj_t *conference, switch_stream_handle_t *stream, int argc, char **argv); switch_status_t conference_api_sub_lock(conference_obj_t *conference, switch_stream_handle_t *stream, int argc, char **argv); switch_status_t conference_api_sub_unlock(conference_obj_t *conference, switch_stream_handle_t *stream, int argc, char **argv); switch_status_t conference_api_sub_relate(conference_obj_t *conference, switch_stream_handle_t *stream, int argc, char **argv); @@ -1307,8 +1313,8 @@ const char *conference_get_variable(conference_obj_t *conference, const char *va /* Entries in this list should be kept in sync with the enum above */ extern api_command_t conference_api_sub_commands[]; extern struct _mapping control_mappings[]; - - +#define stream_write(__stream, __fmt, ...) if (__stream)__stream->write_function(__stream, __fmt, __VA_ARGS__) +#define VA_NONE "%s", "" #endif /* MOD_CONFERENCE_H */ /* For Emacs: diff --git a/src/mod/applications/mod_cv/mod_cv.cpp b/src/mod/applications/mod_cv/mod_cv.cpp index 582f925abf..800452dd9a 100644 --- a/src/mod/applications/mod_cv/mod_cv.cpp +++ b/src/mod/applications/mod_cv/mod_cv.cpp @@ -37,7 +37,7 @@ #include -#include "highgui.h" +#include "opencv2/highgui/highgui_c.h" #include #include #include @@ -596,9 +596,9 @@ void detectAndDraw(cv_context_t *context) context->cascade->detectMultiScale( smallImg, detectedObjs, context->search_scale, context->neighbors, 0 - |CV_HAAR_FIND_BIGGEST_OBJECT - |CV_HAAR_DO_ROUGH_SEARCH - |CV_HAAR_SCALE_IMAGE + |CASCADE_FIND_BIGGEST_OBJECT + |CASCADE_DO_ROUGH_SEARCH + |CASCADE_SCALE_IMAGE , Size(context->max_search_w, context->max_search_h) ); @@ -679,7 +679,7 @@ void detectAndDraw(cv_context_t *context) //|CV_HAAR_FIND_BIGGEST_OBJECT //|CV_HAAR_DO_ROUGH_SEARCH //|CV_HAAR_DO_CANNY_PRUNING - |CV_HAAR_SCALE_IMAGE + |CASCADE_SCALE_IMAGE , Size(30, 30) ); @@ -690,7 +690,7 @@ void detectAndDraw(cv_context_t *context) //printf("WTF %d\n", object_neighbors); //cout << "Detected " << object_neighbors << " object neighbors" << endl; const int rect_height = cvRound((float)img.rows * object_neighbors / max_neighbors); - CvScalar col = CV_RGB((float)255 * object_neighbors / max_neighbors, 0, 0); + cv:Scalar col = CV_RGB((float)255 * object_neighbors / max_neighbors, 0, 0); rectangle(img, cvPoint(0, img.rows), cvPoint(img.cols/10, img.rows - rect_height), col, -1); parse_stats(&context->nestDetected, nestedObjects.size(), context->skip); diff --git a/src/mod/applications/mod_distributor/mod_distributor.c b/src/mod/applications/mod_distributor/mod_distributor.c index a653514f89..47f97f9421 100644 --- a/src/mod/applications/mod_distributor/mod_distributor.c +++ b/src/mod/applications/mod_distributor/mod_distributor.c @@ -403,7 +403,7 @@ SWITCH_STANDARD_API(distributor_ctl_function) if (argc > 0) { if (!strcasecmp(argv[0], "reload")) { if (load_config(SWITCH_TRUE) == SWITCH_STATUS_SUCCESS) { - stream->write_function(stream, "+ok reloaded.\n"); + stream->write_function(stream, "+OK reloaded.\n"); err = NULL; } } else if (!strcasecmp(argv[0], "dump")) { diff --git a/src/mod/applications/mod_dptools/mod_dptools.c b/src/mod/applications/mod_dptools/mod_dptools.c index f35c3cb8f8..b9ef0708d8 100644 --- a/src/mod/applications/mod_dptools/mod_dptools.c +++ b/src/mod/applications/mod_dptools/mod_dptools.c @@ -1,6 +1,6 @@ /* * FreeSWITCH Modular Media Switching Software Library / Soft-Switch Application - * Copyright (C) 2005-2015, Anthony Minessale II + * Copyright (C) 2005-2020, Anthony Minessale II * * Version: MPL 1.1 * @@ -3317,6 +3317,16 @@ SWITCH_STANDARD_APP(record_session_unmask_function) switch_ivr_record_session_mask(session, (char *) data, SWITCH_FALSE); } +SWITCH_STANDARD_APP(record_session_pause_function) +{ + switch_ivr_record_session_pause(session, (char *) data, SWITCH_TRUE); +} + +SWITCH_STANDARD_APP(record_session_resume_function) +{ + switch_ivr_record_session_pause(session, (char *) data, SWITCH_FALSE); +} + SWITCH_STANDARD_APP(record_session_function) { char *array[5] = {0}; @@ -4591,7 +4601,7 @@ SWITCH_STANDARD_APP(wait_for_silence_function) timeout_ms = switch_atoui(argv[3]); } - if (thresh > 0 && silence_hits > 0 && listen_hits > 0) { + if (thresh > 0 && silence_hits > 0 && listen_hits >= 0) { switch_ivr_wait_for_silence(session, thresh, silence_hits, listen_hits, timeout_ms, argv[4]); return; } @@ -6328,6 +6338,52 @@ SWITCH_STANDARD_APP(vad_test_function) switch_core_session_reset(session, SWITCH_TRUE, SWITCH_TRUE); } +#define DEBUG_MEDIA_SYNTAX " " +SWITCH_STANDARD_APP(debug_media_function) +{ + char *mycmd = NULL, *argv[2] = { 0 }; + int argc = 0; + switch_status_t status = SWITCH_STATUS_FALSE; + + if (!zstr(data) && (mycmd = strdup(data))) { + argc = switch_separate_string(mycmd, ' ', argv, (sizeof(argv) / sizeof(argv[0]))); + } + + if (zstr(data) || argc < 2 || zstr(argv[0]) || zstr(argv[1])) { + switch_log_printf(SWITCH_CHANNEL_SESSION_LOG(session), SWITCH_LOG_ERROR, "USAGE: %s\n", DEBUG_MEDIA_SYNTAX); + goto done; + } else { + switch_core_session_message_t msg = { 0 }; + + msg.message_id = SWITCH_MESSAGE_INDICATE_DEBUG_MEDIA; + msg.string_array_arg[0] = argv[0]; + msg.string_array_arg[1] = argv[1]; + msg.from = __FILE__; + + if (!strcasecmp(argv[0], "all")) { + msg.string_array_arg[0] = "both"; + } + + again: + status = switch_core_session_receive_message(session, &msg); + + if (status == SWITCH_STATUS_SUCCESS && !strcasecmp(argv[0], "all") && !strcmp(msg.string_array_arg[0], "both")) { + msg.string_array_arg[0] = "vboth"; + goto again; + } + } + + if (status == SWITCH_STATUS_SUCCESS) { + switch_log_printf(SWITCH_CHANNEL_SESSION_LOG(session), SWITCH_LOG_DEBUG, "media debug on\n"); + } else { + switch_log_printf(SWITCH_CHANNEL_SESSION_LOG(session), SWITCH_LOG_DEBUG, "error to turn on media debug status=%d\n", status); + } + + done: + + switch_safe_free(mycmd); +} + #define SPEAK_DESC "Speak text to a channel via the tts interface" #define DISPLACE_DESC "Displace audio from a file to the channels input" #define SESS_REC_DESC "Starts a background recording of the entire session" @@ -6371,6 +6427,11 @@ SWITCH_MODULE_LOAD_FUNCTION(mod_dptools_load) switch_dialplan_interface_t *dp_interface; switch_chat_interface_t *chat_interface; switch_file_interface_t *file_interface; + int use_system_commands = 1; + + if (switch_true(switch_core_get_variable("disable_system_app_commands"))) { + use_system_commands = 0; + } if (switch_event_reserve_subclass(FILE_STRING_CLOSE) != SWITCH_STATUS_SUCCESS) { switch_log_printf(SWITCH_CHANNEL_LOG, SWITCH_LOG_ERROR, "Couldn't register subclass %s!\n", FILE_STRING_CLOSE); @@ -6633,7 +6694,9 @@ SWITCH_MODULE_LOAD_FUNCTION(mod_dptools_load) SWITCH_ADD_APP(app_interface, "stop_record_session", "Stop Record Session", STOP_SESS_REC_DESC, stop_record_session_function, "", SAF_NONE); SWITCH_ADD_APP(app_interface, "record_session", "Record Session", SESS_REC_DESC, record_session_function, " [+]", SAF_MEDIA_TAP); SWITCH_ADD_APP(app_interface, "record_session_mask", "Mask audio in recording", SESS_REC_MASK_DESC, record_session_mask_function, "", SAF_MEDIA_TAP); - SWITCH_ADD_APP(app_interface, "record_session_unmask", "Resume recording", SESS_REC_UNMASK_DESC, record_session_unmask_function, "", SAF_MEDIA_TAP); + SWITCH_ADD_APP(app_interface, "record_session_unmask", "Stop masking audio in recording", SESS_REC_UNMASK_DESC, record_session_unmask_function, "", SAF_MEDIA_TAP); + SWITCH_ADD_APP(app_interface, "record_session_pause", "Pause recording", "Temporarily pause writing call recording audio to file", record_session_pause_function, "", SAF_MEDIA_TAP); + SWITCH_ADD_APP(app_interface, "record_session_resume", "Resume paused recording", "Resume writing call recording audio to file", record_session_resume_function, "", SAF_MEDIA_TAP); SWITCH_ADD_APP(app_interface, "record", "Record File", "Record a file from the channels input", record_function, " [] [] []", SAF_NONE); SWITCH_ADD_APP(app_interface, "preprocess", "pre-process", "pre-process", preprocess_session_function, "", SAF_NONE); @@ -6646,10 +6709,12 @@ SWITCH_MODULE_LOAD_FUNCTION(mod_dptools_load) SAF_NONE); SWITCH_ADD_APP(app_interface, "bridge", "Bridge Audio", "Bridge the audio between two sessions", audio_bridge_function, "", SAF_SUPPORT_NOMEDIA|SAF_SUPPORT_TEXT_ONLY); - SWITCH_ADD_APP(app_interface, "system", "Execute a system command", "Execute a system command", system_session_function, "", - SAF_SUPPORT_NOMEDIA | SAF_ZOMBIE_EXEC); - SWITCH_ADD_APP(app_interface, "bgsystem", "Execute a system command in the background", "Execute a background system command", bgsystem_session_function, "", - SAF_SUPPORT_NOMEDIA | SAF_ZOMBIE_EXEC); + if (use_system_commands) { + SWITCH_ADD_APP(app_interface, "system", "Execute a system command", "Execute a system command", system_session_function, "", + SAF_SUPPORT_NOMEDIA | SAF_ZOMBIE_EXEC); + SWITCH_ADD_APP(app_interface, "bgsystem", "Execute a system command in the background", "Execute a background system command", bgsystem_session_function, "", + SAF_SUPPORT_NOMEDIA | SAF_ZOMBIE_EXEC); + } SWITCH_ADD_APP(app_interface, "say", "say", "say", say_function, SAY_SYNTAX, SAF_NONE); SWITCH_ADD_APP(app_interface, "detect_audio", "detect_audio", "detect_audio", detect_audio_function, DETECT_AUDIO_SYNTAX, @@ -6669,6 +6734,7 @@ SWITCH_MODULE_LOAD_FUNCTION(mod_dptools_load) SWITCH_ADD_APP(app_interface, "deduplicate_dtmf", "Prevent duplicate inband + 2833 dtmf", "", deduplicate_dtmf_app_function, "[only_rtp]", SAF_SUPPORT_NOMEDIA); SWITCH_ADD_APP(app_interface, "vad_test", "VAD test", "VAD test, mode = -1(default), 0, 1, 2, 3", vad_test_function, "[mode]", SAF_NONE); + SWITCH_ADD_APP(app_interface, "debug_media", "Debug Media", "Debug Media", debug_media_function, DEBUG_MEDIA_SYNTAX, SAF_SUPPORT_NOMEDIA); SWITCH_ADD_DIALPLAN(dp_interface, "inline", inline_dialplan_hunt); diff --git a/src/mod/applications/mod_fifo/mod_fifo.c b/src/mod/applications/mod_fifo/mod_fifo.c index 0f9d1b299d..724d1dd24f 100644 --- a/src/mod/applications/mod_fifo/mod_fifo.c +++ b/src/mod/applications/mod_fifo/mod_fifo.c @@ -458,62 +458,6 @@ static int sql2str_callback(void *pArg, int argc, char **argv, char **columnName return 0; } -/*!\brief Handler for consumer DTMF - * - * When `fifo_consumer_exit_key` is pressed by the consumer we hangup - * on the caller (unless we've put the caller on hold). The default - * exit key is '*'. - * - * When the consumer presses '0' we put both legs on hold and play - * hold music as follows. To the caller we play `fifo_music` or the - * default hold music for the channel. To the consumer we play - * `fifo_hold_music`, or `fifo_music`, or the default hold music for - * the channel. The consumer can press '0' again to pick up the - * caller from hold. - */ -static switch_status_t on_dtmf(switch_core_session_t *session, void *input, switch_input_type_t itype, void *buf, unsigned int buflen) -{ - switch_core_session_t *bleg = (switch_core_session_t *) buf; - - switch (itype) { - case SWITCH_INPUT_TYPE_DTMF: - { - switch_dtmf_t *dtmf = (switch_dtmf_t *) input; - switch_channel_t *bchan = switch_core_session_get_channel(bleg); - switch_channel_t *channel = switch_core_session_get_channel(session); - - if (switch_channel_test_flag(switch_core_session_get_channel(session), CF_BRIDGE_ORIGINATOR)) { - const char *consumer_exit_key = switch_channel_get_variable(channel, "fifo_consumer_exit_key"); - if (!consumer_exit_key) consumer_exit_key = "*"; - if (dtmf->digit == *consumer_exit_key) { - switch_channel_hangup(bchan, SWITCH_CAUSE_NORMAL_CLEARING); - return SWITCH_STATUS_BREAK; - } else if (dtmf->digit == '0') { - const char *moh_a = NULL, *moh_b = NULL; - - if (!(moh_b = switch_channel_get_variable(bchan, "fifo_music"))) { - moh_b = switch_channel_get_hold_music(bchan); - } - - if (!(moh_a = switch_channel_get_variable(channel, "fifo_hold_music"))) { - if (!(moh_a = switch_channel_get_variable(channel, "fifo_music"))) { - moh_a = switch_channel_get_hold_music(channel); - } - } - - switch_ivr_soft_hold(session, "0", moh_a, moh_b); - return SWITCH_STATUS_IGNORE; - } - } - } - break; - default: - break; - } - - return SWITCH_STATUS_SUCCESS; -} - /*!\brief Handler for caller DTMF * * The channel variable `fifo_caller_exit_key` can be set to one or @@ -723,8 +667,66 @@ static struct { int allow_transcoding; switch_bool_t delete_all_members_on_startup; outbound_strategy_t default_strategy; + int disable_dtmf_moh_key; } globals; + +/*!\brief Handler for consumer DTMF + * + * When `fifo_consumer_exit_key` is pressed by the consumer we hangup + * on the caller (unless we've put the caller on hold). The default + * exit key is '*'. + * + * When the consumer presses '0' we put both legs on hold and play + * hold music as follows. To the caller we play `fifo_music` or the + * default hold music for the channel. To the consumer we play + * `fifo_hold_music`, or `fifo_music`, or the default hold music for + * the channel. The consumer can press '0' again to pick up the + * caller from hold. + */ +static switch_status_t on_dtmf(switch_core_session_t *session, void *input, switch_input_type_t itype, void *buf, unsigned int buflen) +{ + switch_core_session_t *bleg = (switch_core_session_t *) buf; + + switch (itype) { + case SWITCH_INPUT_TYPE_DTMF: + { + switch_dtmf_t *dtmf = (switch_dtmf_t *) input; + switch_channel_t *bchan = switch_core_session_get_channel(bleg); + switch_channel_t *channel = switch_core_session_get_channel(session); + + if (switch_channel_test_flag(switch_core_session_get_channel(session), CF_BRIDGE_ORIGINATOR)) { + const char *consumer_exit_key = switch_channel_get_variable(channel, "fifo_consumer_exit_key"); + if (!consumer_exit_key) consumer_exit_key = "*"; + if (dtmf->digit == *consumer_exit_key) { + switch_channel_hangup(bchan, SWITCH_CAUSE_NORMAL_CLEARING); + return SWITCH_STATUS_BREAK; + } else if (dtmf->digit == '0' && !globals.disable_dtmf_moh_key) { + const char *moh_a = NULL, *moh_b = NULL; + + if (!(moh_b = switch_channel_get_variable(bchan, "fifo_music"))) { + moh_b = switch_channel_get_hold_music(bchan); + } + + if (!(moh_a = switch_channel_get_variable(channel, "fifo_hold_music"))) { + if (!(moh_a = switch_channel_get_variable(channel, "fifo_music"))) { + moh_a = switch_channel_get_hold_music(channel); + } + } + + switch_ivr_soft_hold(session, "0", moh_a, moh_b); + return SWITCH_STATUS_IGNORE; + } + } + } + break; + default: + break; + } + + return SWITCH_STATUS_SUCCESS; +} + static int fifo_dec_use_count(const char *outbound_id) { int r = 0, *count; @@ -2550,7 +2552,7 @@ typedef enum { #define MAX_NODES_PER_CONSUMER 25 #define FIFO_DESC "Fifo for stacking parked calls." -#define FIFO_USAGE "[!] [in [|undef] [|undef] | out [wait|nowait] [|undef] [|undef]]" +#define FIFO_USAGE "[!] [in [|undef] [|undef] [early|noans] | out [wait|nowait] [|undef] [|undef]]" SWITCH_STANDARD_APP(fifo_function) { int argc; @@ -2568,7 +2570,7 @@ SWITCH_STANDARD_APP(fifo_function) char *list_string; int nlist_count; char *nlist[MAX_NODES_PER_CONSUMER]; - int consumer = 0, in_table = 0; + int consumer = 0, in_table = 0, answer = 0; const char *arg_fifo_name = NULL; const char *arg_inout = NULL; const char *serviced_uuid = NULL; @@ -2658,6 +2660,13 @@ SWITCH_STANDARD_APP(fifo_function) if (argc > 3) { moh = argv[3]; } + if (argc > 4) { + if (!strcasecmp(argv[4], "noans")) { + answer = 1; + } else if (!strcasecmp(argv[4], "early")) { + answer = 2; + } + } } if (moh && !strcasecmp(moh, "silence")) { @@ -2714,7 +2723,9 @@ SWITCH_STANDARD_APP(fifo_function) } } - switch_channel_answer(channel); + if (answer == 0) { + switch_channel_answer(channel); + } switch_mutex_lock(node->update_mutex); @@ -2965,7 +2976,9 @@ SWITCH_STANDARD_APP(fifo_function) switch_core_hash_insert(node->consumer_hash, switch_core_session_get_uuid(session), session); switch_mutex_unlock(node->mutex); } - switch_channel_answer(channel); + if( answer == 0 ) { + switch_channel_answer(channel); + } } if (switch_event_create_subclass(&event, SWITCH_EVENT_CUSTOM, FIFO_EVENT) == SWITCH_STATUS_SUCCESS) { @@ -3295,7 +3308,9 @@ SWITCH_STANDARD_APP(fifo_function) break; } - switch_channel_answer(channel); + if (answer == 0 || answer == 2) { + switch_channel_answer(channel); + } if (switch_channel_inbound_display(other_channel)) { if (switch_channel_direction(other_channel) == SWITCH_CALL_DIRECTION_INBOUND) { @@ -4405,6 +4420,8 @@ static switch_status_t read_config_file(switch_xml_t *xml, switch_xml_t *cfg) { globals.inner_post_trans_execute = switch_core_strdup(globals.pool, val); } else if (!strcasecmp(var, "delete-all-outbound-member-on-startup")) { globals.delete_all_members_on_startup = switch_true(val); + } else if (!strcasecmp(var, "disable-dtmf-moh-key") && !zstr(val)) { + globals.disable_dtmf_moh_key = switch_true(val); } } } diff --git a/src/mod/applications/mod_fsv/mod_fsv.c b/src/mod/applications/mod_fsv/mod_fsv.c index 8a21e0721d..90d64972ad 100644 --- a/src/mod/applications/mod_fsv/mod_fsv.c +++ b/src/mod/applications/mod_fsv/mod_fsv.c @@ -786,15 +786,26 @@ struct fsv_file_context { switch_file_t *fd; char *path; switch_mutex_t *mutex; + switch_queue_t *video_queue; + switch_codec_t video_codec; + switch_image_t *last_img; + switch_bool_t no_video_decode; + uint8_t video_packet_buffer[SWITCH_RECOMMENDED_BUFFER_SIZE]; }; typedef struct fsv_file_context fsv_file_context; +typedef struct fsv_file_video_packet_s { + uint8_t *data; + uint32_t len; +} fsv_file_video_packet_t; + static switch_status_t fsv_file_open(switch_file_handle_t *handle, const char *path) { fsv_file_context *context; char *ext; unsigned int flags = 0; + const char *video_codec = NULL; if ((ext = strrchr(path, '.')) == 0) { switch_log_printf(SWITCH_CHANNEL_LOG, SWITCH_LOG_ERROR, "Invalid Format\n"); @@ -827,6 +838,8 @@ static switch_status_t fsv_file_open(switch_file_handle_t *handle, const char *p return SWITCH_STATUS_GENERR; } + switch_queue_create(&context->video_queue, 500, handle->memory_pool); + context->path = switch_core_strdup(handle->memory_pool, path); if (switch_test_flag(handle, SWITCH_FILE_WRITE_APPEND)) { @@ -836,8 +849,6 @@ static switch_status_t fsv_file_open(switch_file_handle_t *handle, const char *p } handle->samples = 0; - // handle->samplerate = 8000; - // handle->channels = 1; handle->format = 0; handle->sections = 0; handle->seekable = 0; @@ -846,6 +857,8 @@ static switch_status_t fsv_file_open(switch_file_handle_t *handle, const char *p handle->private_info = context; switch_log_printf(SWITCH_CHANNEL_LOG, SWITCH_LOG_INFO, "Opening File [%s] %dhz\n", path, handle->samplerate); + context->no_video_decode = switch_true(switch_event_get_header(handle->params, "no_video_decode")); + if (switch_test_flag(handle, SWITCH_FILE_FLAG_WRITE)) { struct file_header h; size_t len = sizeof(h); @@ -855,7 +868,9 @@ static switch_status_t fsv_file_open(switch_file_handle_t *handle, const char *p h.version = VERSION; h.created = switch_micro_time_now(); - switch_set_string(h.video_codec_name, "H264"); /* FIXME: hard coded */ + video_codec = switch_event_get_header(handle->params, "video_codec_name"); + if (zstr(video_codec)) video_codec = "VP8"; + switch_set_string(h.video_codec_name, video_codec); h.audio_rate = handle->samplerate; h.audio_ptime = 20; /* FIXME: hard coded */ @@ -879,8 +894,28 @@ static switch_status_t fsv_file_open(switch_file_handle_t *handle, const char *p } handle->samplerate = h.audio_rate; + handle->channels = h.channels; + video_codec = switch_core_strdup(handle->memory_pool, h.video_codec_name); } + if (video_codec && !context->no_video_decode) { + if (switch_core_codec_init(&context->video_codec, + video_codec, + NULL, + NULL, + 90000, + 0, + 0, SWITCH_CODEC_FLAG_ENCODE | SWITCH_CODEC_FLAG_DECODE, + NULL, handle->memory_pool) != SWITCH_STATUS_SUCCESS) { + switch_log_printf(SWITCH_CHANNEL_LOG, SWITCH_LOG_WARNING, "Video Codec Activation Failed\n"); + } else { + switch_log_printf(SWITCH_CHANNEL_LOG, SWITCH_LOG_INFO, "Video Codec [%s] ready\n", video_codec); + } + } + + switch_log_printf(SWITCH_CHANNEL_LOG, SWITCH_LOG_INFO, "File opened [%s] %dhz [%d] channels, no_video_decode=%s\n", + path, handle->samplerate, handle->channels, context->no_video_decode ? "true" : "false"); + return SWITCH_STATUS_SUCCESS; } @@ -908,6 +943,20 @@ static switch_status_t fsv_file_close(switch_file_handle_t *handle) context->fd = NULL; } + if (switch_test_flag(&context->video_codec, SWITCH_CODEC_FLAG_READY)) { + switch_core_codec_destroy(&context->video_codec); + } + + if (context->video_queue) { + void *pop; + + while (switch_queue_trypop(context->video_queue, &pop) == SWITCH_STATUS_SUCCESS) { + free(pop); + } + } + + switch_img_free(&context->last_img); + return SWITCH_STATUS_SUCCESS; } @@ -920,7 +969,7 @@ static switch_status_t fsv_file_seek(switch_file_handle_t *handle, unsigned int static switch_status_t fsv_file_read(switch_file_handle_t *handle, void *data, size_t *len) { switch_status_t status; - size_t need = *len; + size_t need = *len * 2; uint32_t size; size_t bytes = sizeof(size); fsv_file_context *context = handle->private_info; @@ -934,15 +983,31 @@ again: } if (size & VID_BIT) { /* video */ - *len = size & ~VID_BIT; - /* TODO: read video data */ - switch_log_printf(SWITCH_CHANNEL_LOG, SWITCH_LOG_WARNING, "discarding video data %d\n", (int)*len); - status = switch_file_read(context->fd, data, len); + uint8_t *video_data = malloc(sizeof(size) + size); + switch_size_t read_size; - if (status != SWITCH_STATUS_SUCCESS) { + switch_assert(video_data); + size &= ~VID_BIT; + read_size = size; + *(uint32_t *)video_data = size; + + status = switch_file_read(context->fd, video_data + sizeof(size), &read_size); + + if (status != SWITCH_STATUS_SUCCESS || read_size != size) { + switch_log_printf(SWITCH_CHANNEL_LOG, SWITCH_LOG_ERROR, + "read error status=%d size=%u read_size=%" SWITCH_SIZE_T_FMT "\n", + status, size, read_size); + free(video_data); goto end; } + switch_mutex_lock(context->mutex); + if (switch_queue_trypush(context->video_queue, video_data) != SWITCH_STATUS_SUCCESS) { + switch_log_printf(SWITCH_CHANNEL_LOG, SWITCH_LOG_WARNING, "queue overflow!!\n"); + free(video_data); + } + switch_mutex_unlock(context->mutex); + handle->pos += *len + bytes; goto again; } @@ -963,6 +1028,126 @@ end: return status; } +static switch_status_t fsv_file_read_video(switch_file_handle_t *handle, switch_frame_t *frame, switch_video_read_flag_t flags) +{ + fsv_file_context *context = handle->private_info; + switch_image_t *dup = NULL; + switch_status_t status = SWITCH_STATUS_SUCCESS; + void *video_packet = NULL; + switch_time_t start = switch_time_now(); + switch_status_t decode_status = SWITCH_STATUS_MORE_DATA; + int new_img = 0; + + if ((flags & SVR_CHECK)) { + switch_goto_status(SWITCH_STATUS_BREAK, end); + } + + if (context->no_video_decode) { // read video without decode + uint32_t size; + switch_rtp_hdr_t *rtp; + + while (1) { + switch_mutex_lock(context->mutex); + status = switch_queue_trypop(context->video_queue, &video_packet); + switch_mutex_unlock(context->mutex); + + if (status != SWITCH_STATUS_SUCCESS || !video_packet) { + switch_safe_free(video_packet); + if (flags & SVR_BLOCK) { + if (switch_time_now() - start < 33000) { + switch_yield(10000); + continue; + } + } + return SWITCH_STATUS_BREAK; + } + + break; + } + + size = *(uint32_t *)video_packet; + if (size > sizeof(context->video_packet_buffer)) { + free(video_packet); + return SWITCH_STATUS_BREAK; + } + + memcpy(context->video_packet_buffer, (uint8_t *)video_packet + sizeof(uint32_t), size); + free(video_packet); + video_packet = NULL; + + rtp = (switch_rtp_hdr_t *)context->video_packet_buffer; + frame->packet = context->video_packet_buffer; + frame->packetlen = size; + frame->data = context->video_packet_buffer + 12; + frame->datalen = size - 12; + frame->m = rtp->m; + frame->timestamp = ntohl(rtp->ts); + frame->flags = SFF_RAW_RTP | SFF_RTP_HEADER | SFF_ENCODED; + + return SWITCH_STATUS_SUCCESS; + } + + while (!new_img) { + while (decode_status == SWITCH_STATUS_MORE_DATA || decode_status == SWITCH_STATUS_SUCCESS) { + switch_frame_t rtp_frame = { 0 }; + uint32_t size; + switch_rtp_hdr_t *rtp; + + switch_mutex_lock(context->mutex); + status = switch_queue_trypop(context->video_queue, &video_packet); + switch_mutex_unlock(context->mutex); + + if (status != SWITCH_STATUS_SUCCESS || !video_packet) break; + + size = *(uint32_t *)video_packet; + rtp = (switch_rtp_hdr_t *)((uint8_t *)video_packet + sizeof(uint32_t)); + + rtp_frame.packet = rtp; + rtp_frame.packetlen = size; + rtp_frame.data = (uint8_t *)rtp_frame.packet + 12; + rtp_frame.datalen = size - 12; + rtp_frame.m = rtp->m; + rtp_frame.timestamp = ntohl(rtp->ts); + decode_status = switch_core_codec_decode_video(&context->video_codec, &rtp_frame); + rtp_frame.packet = NULL; + rtp_frame.data = NULL; + rtp_frame.datalen = 0; + rtp_frame.packetlen = 0; + free(video_packet); + + if (rtp_frame.img) { + switch_img_copy(rtp_frame.img, &context->last_img); + new_img = 1; + break; + } else if (rtp_frame.m) { + break; + } + } + + if (!(flags & SVR_BLOCK)) { + break; + } + + if (switch_time_now() - start < 33000) { + switch_yield(10000); + } else { + break; + } + } + + if (context->last_img) { + switch_img_copy(context->last_img, &dup); + frame->img = dup; + status = SWITCH_STATUS_SUCCESS; + } else { + status = SWITCH_STATUS_BREAK; + } + + end: + + return status; +} + static switch_status_t fsv_file_write(switch_file_handle_t *handle, void *data, size_t *len) { uint32_t datalen = (uint32_t)(*len * sizeof(int16_t)); @@ -1071,6 +1256,7 @@ SWITCH_MODULE_LOAD_FUNCTION(mod_fsv_load) file_interface->file_close = fsv_file_close; file_interface->file_truncate = fsv_file_truncate; file_interface->file_read = fsv_file_read; + file_interface->file_read_video = fsv_file_read_video; file_interface->file_write = fsv_file_write; #if 0 file_interface->file_write_video = fsv_file_write_video; diff --git a/src/mod/applications/mod_hash/mod_hash.c b/src/mod/applications/mod_hash/mod_hash.c index 6899922ab6..70bffd18e1 100644 --- a/src/mod/applications/mod_hash/mod_hash.c +++ b/src/mod/applications/mod_hash/mod_hash.c @@ -144,10 +144,7 @@ SWITCH_LIMIT_INCR(limit_incr_hash) if (!(item = (limit_hash_item_t *) switch_core_hash_find(globals.limit_hash, hashkey))) { /* No, create an empty structure and add it, then continue like as if it existed */ switch_log_printf(SWITCH_CHANNEL_SESSION_LOG(session), SWITCH_LOG_DEBUG10, "Creating new limit structure: key: %s\n", hashkey); - item = (limit_hash_item_t *) malloc(sizeof(limit_hash_item_t)); - switch_assert(item); - memset(item, 0, sizeof(limit_hash_item_t)); - switch_core_hash_insert(globals.limit_hash, hashkey, item); + item = (limit_hash_item_t *)switch_core_hash_insert_alloc(globals.limit_hash, hashkey, sizeof(limit_hash_item_t)); } if (!(pvt = switch_channel_get_private(channel, "limit_hash"))) { @@ -433,17 +430,13 @@ SWITCH_STANDARD_APP(hash_function) free(value); switch_core_hash_delete(globals.db_hash, hash_key); } - value = strdup(argv[3]); - switch_assert(value); - switch_core_hash_insert(globals.db_hash, hash_key, value); + switch_core_hash_insert_dup(globals.db_hash, hash_key, argv[3]); } else if (!strcasecmp(argv[0], "insert_ifempty")) { if (argc < 4) { goto usage; } if (!(value = switch_core_hash_find(globals.db_hash, hash_key))) { - value = strdup(argv[3]); - switch_assert(value); - switch_core_hash_insert(globals.db_hash, hash_key, value); + switch_core_hash_insert_dup(globals.db_hash, hash_key, argv[3]); } } else if (!strcasecmp(argv[0], "delete")) { @@ -506,9 +499,7 @@ SWITCH_STANDARD_API(hash_api_function) switch_safe_free(value); switch_core_hash_delete(globals.db_hash, hash_key); } - value = strdup(argv[3]); - switch_assert(value); - switch_core_hash_insert(globals.db_hash, hash_key, value); + switch_core_hash_insert_dup(globals.db_hash, hash_key, argv[3]); stream->write_function(stream, "+OK\n"); switch_thread_rwlock_unlock(globals.db_hash_rwlock); } else if (!strcasecmp(argv[0], "insert_ifempty")) { @@ -519,9 +510,7 @@ SWITCH_STANDARD_API(hash_api_function) if ((value = switch_core_hash_find(globals.db_hash, hash_key))) { stream->write_function(stream, "-ERR key already exists\n"); } else { - value = strdup(argv[3]); - switch_assert(value); - switch_core_hash_insert(globals.db_hash, hash_key, value); + switch_core_hash_insert_dup(globals.db_hash, hash_key, argv[3]); stream->write_function(stream, "+OK\n"); } switch_thread_rwlock_unlock(globals.db_hash_rwlock); diff --git a/src/mod/applications/mod_httapi/mod_httapi.c b/src/mod/applications/mod_httapi/mod_httapi.c index cc2c857a58..0b89fd35a7 100644 --- a/src/mod/applications/mod_httapi/mod_httapi.c +++ b/src/mod/applications/mod_httapi/mod_httapi.c @@ -2430,6 +2430,13 @@ static char *load_cache_data(http_file_context_t *context, const char *url) return context->cache_file; } +static size_t dummy_save_file_callback(void* ptr, size_t size, size_t nmemb, void* data) +{ + (void)ptr; + (void)data; + return (size * nmemb); +} + static size_t save_file_callback(void *ptr, size_t size, size_t nmemb, void *data) { register unsigned int realsize = (unsigned int) (size * nmemb); @@ -2616,19 +2623,20 @@ static switch_status_t fetch_cache_data(http_file_context_t *context, const char } else { switch_curl_easy_setopt(curl_handle, CURLOPT_HEADER, 1); switch_curl_easy_setopt(curl_handle, CURLOPT_NOBODY, 1); + + /* Prevent writing the data (headers in this case) to stdout */ + switch_curl_easy_setopt(curl_handle, CURLOPT_WRITEFUNCTION, dummy_save_file_callback); + switch_curl_easy_setopt(curl_handle, CURLOPT_WRITEDATA, 0); } if (headers) { if (!client->headers) { switch_event_create(&client->headers, SWITCH_EVENT_CLONE); } - if (save_path) { - switch_curl_easy_setopt(curl_handle, CURLOPT_HEADERFUNCTION, get_header_callback); - switch_curl_easy_setopt(curl_handle, CURLOPT_WRITEHEADER, (void *) client); - } else { - switch_curl_easy_setopt(curl_handle, CURLOPT_WRITEFUNCTION, get_header_callback); - switch_curl_easy_setopt(curl_handle, CURLOPT_WRITEDATA, (void *) client); - } + + /* CURLOPT_HEADERFUNCTION guarantees to call the callback for each complete header line, CURLOPT_WRITEFUNCTION does not! */ + switch_curl_easy_setopt(curl_handle, CURLOPT_HEADERFUNCTION, get_header_callback); + switch_curl_easy_setopt(curl_handle, CURLOPT_WRITEHEADER, (void *) client); } if (!zstr(dup_creds)) { @@ -2885,13 +2893,21 @@ static switch_status_t locate_url_file(http_file_context_t *context, const char static switch_status_t http_file_file_seek(switch_file_handle_t *handle, unsigned int *cur_sample, int64_t samples, int whence) { http_file_context_t *context = handle->private_info; - + switch_status_t status; + if (!handle->seekable) { switch_log_printf(SWITCH_CHANNEL_LOG, SWITCH_LOG_WARNING, "File is not seekable\n"); return SWITCH_STATUS_NOTIMPL; } - return switch_core_file_seek(&context->fh, cur_sample, samples, whence); + if ((status = switch_core_file_seek(&context->fh, cur_sample, samples, whence)) == SWITCH_STATUS_SUCCESS) { + handle->pos = context->fh.pos; + handle->offset_pos = context->fh.offset_pos; + handle->samples_in = context->fh.samples_in; + handle->samples_out = context->fh.samples_out; + } + + return status; } static switch_status_t file_open(switch_file_handle_t *handle, const char *path, int is_https) diff --git a/src/mod/applications/mod_http_cache/mod_http_cache.c b/src/mod/applications/mod_http_cache/mod_http_cache.c index dcf1d7bff5..d6f4fb6ed8 100644 --- a/src/mod/applications/mod_http_cache/mod_http_cache.c +++ b/src/mod/applications/mod_http_cache/mod_http_cache.c @@ -781,7 +781,7 @@ static char *url_cache_get(url_cache_t *cache, http_profile_t *profile, switch_c switch_log_printf(SWITCH_CHANNEL_SESSION_LOG(session), SWITCH_LOG_INFO, "Waiting for URL %s to be available\n", url); u->waiters++; url_cache_unlock(cache, session); - while(u->status == CACHED_URL_RX_IN_PROGRESS && switch_time_now() < (u->download_time + download_timeout_ns)) { + while(!gcache.shutdown && u->status == CACHED_URL_RX_IN_PROGRESS && switch_time_now() < (u->download_time + download_timeout_ns)) { switch_sleep(10 * 1000); /* 10 ms */ } url_cache_lock(cache, session); @@ -1936,13 +1936,22 @@ static switch_status_t http_file_close(switch_file_handle_t *handle) static switch_status_t http_cache_file_seek(switch_file_handle_t *handle, unsigned int *cur_sample, int64_t samples, int whence) { - struct http_context *context = (struct http_context *)handle->private_info; + struct http_context *context = (struct http_context *)handle->private_info; + switch_status_t status; + + if (!handle->seekable) { + switch_log_printf(SWITCH_CHANNEL_LOG, SWITCH_LOG_WARNING, "File is not seekable\n"); + return SWITCH_STATUS_NOTIMPL; + } - if (!handle->seekable) { - switch_log_printf(SWITCH_CHANNEL_LOG, SWITCH_LOG_WARNING, "File is not seekable\n"); - return SWITCH_STATUS_NOTIMPL; - } - return switch_core_file_seek(&context->fh, cur_sample, samples, whence); + if ((status = switch_core_file_seek(&context->fh, cur_sample, samples, whence)) == SWITCH_STATUS_SUCCESS) { + handle->pos = context->fh.pos; + handle->offset_pos = context->fh.offset_pos; + handle->samples_in = context->fh.samples_in; + handle->samples_out = context->fh.samples_out; + } + + return status; } static char *http_supported_formats[] = { "http", NULL }; diff --git a/src/mod/applications/mod_http_cache/test/test_aws.c b/src/mod/applications/mod_http_cache/test/test_aws.c index bc857af067..d1844f9160 100644 --- a/src/mod/applications/mod_http_cache/test/test_aws.c +++ b/src/mod/applications/mod_http_cache/test/test_aws.c @@ -184,9 +184,7 @@ FST_TEST_END() FST_TEST_BEGIN(get_time) { - char time_stamp[TIME_STAMP_LENGTH]; char date_stamp[DATE_STAMP_LENGTH]; - char time_stamp_test[TIME_STAMP_LENGTH]; char date_stamp_test[DATE_STAMP_LENGTH]; // Get date and time for test case @@ -197,16 +195,13 @@ FST_TEST_BEGIN(get_time) // Get date and time to test get_time("%Y%m%d", date_stamp, DATE_STAMP_LENGTH); - get_time("%Y%m%dT%H%M%SZ", time_stamp, TIME_STAMP_LENGTH); // https://fresh2refresh.com/c-programming/c-time-related-functions/ // https://stackoverflow.com/questions/5141960/get-the-current-time-in-c/5142028 // https://linux.die.net/man/3/ctime // https://stackoverflow.com/questions/153890/printing-leading-0s-in-c switch_snprintf(date_stamp_test, DATE_STAMP_LENGTH, "%d%02d%02d", timeinfo->tm_year + 1900, timeinfo->tm_mon + 1, timeinfo->tm_mday); - switch_snprintf(time_stamp_test, TIME_STAMP_LENGTH, "%d%02d%02dT%02d%02d%02dZ", timeinfo->tm_year + 1900, timeinfo->tm_mon + 1, timeinfo->tm_mday, timeinfo->tm_hour, timeinfo->tm_min, timeinfo->tm_sec); - fst_check_string_equals(time_stamp_test, time_stamp); fst_check_string_equals(date_stamp_test, date_stamp); } FST_TEST_END() diff --git a/src/mod/applications/mod_signalwire/mod_signalwire.c b/src/mod/applications/mod_signalwire/mod_signalwire.c index cabdf4bcc1..466adfa745 100644 --- a/src/mod/applications/mod_signalwire/mod_signalwire.c +++ b/src/mod/applications/mod_signalwire/mod_signalwire.c @@ -76,6 +76,7 @@ static struct { char blade_bootstrap[1024]; char adoption_service[1024]; char stun_server[1024]; + switch_port_t stun_port; char adoption_token[64]; char override_context[64]; ks_size_t adoption_backoff; @@ -319,7 +320,7 @@ static ks_status_t mod_signalwire_adoption_post(void) external_ip = globals.adoption_data_local_ip; external_port = local_port; - if (switch_stun_lookup(&external_ip, &external_port, globals.stun_server, SWITCH_STUN_DEFAULT_PORT, &error, pool) != SWITCH_STATUS_SUCCESS) { + if (switch_stun_lookup(&external_ip, &external_port, globals.stun_server, globals.stun_port, &error, pool) != SWITCH_STATUS_SUCCESS) { switch_log_printf(SWITCH_CHANNEL_LOG, SWITCH_LOG_ERROR, "SignalWire adoption failed: stun [%s] lookup error: %s\n", globals.stun_server, error); status = KS_STATUS_FAIL; goto done; @@ -714,7 +715,8 @@ static switch_status_t load_config() switch_set_string(globals.blade_bootstrap, "edge..signalwire.com/api/relay/wss"); switch_set_string(globals.adoption_service, "https://adopt.signalwire.com/adoption"); switch_set_string(globals.stun_server, "stun.freeswitch.org"); - + globals.stun_port = SWITCH_STUN_DEFAULT_PORT; + if (!(xml = switch_xml_open_cfg(cf, &cfg, NULL))) { switch_log_printf(SWITCH_CHANNEL_LOG, SWITCH_LOG_DEBUG1, "open of %s failed\n", cf); // don't need the config @@ -736,7 +738,20 @@ static switch_status_t load_config() } else if (!strcasecmp(var, "adoption-service") && !ks_zstr(val)) { switch_set_string(globals.adoption_service, val); } else if (!strcasecmp(var, "stun-server") && !ks_zstr(val)) { - switch_set_string(globals.stun_server, val); + char *p, *ss = strdup(val); + + if ((p = strchr(ss, ':'))) { + int port; + *p++ = '\0'; + + port = atoi(p); + if (port > 0 && port < 65536) { + globals.stun_port = port; + } + } + + switch_set_string(globals.stun_server, ss); + switch_safe_free(ss); } else if (!strcasecmp(var, "ssl-verify")) { globals.ssl_verify = switch_true(val) ? 1 : 0; } else if (!strcasecmp(var, "override-context") && !ks_zstr(val)) { @@ -1181,7 +1196,7 @@ static void mod_signalwire_state_configure(void) external_ip = local_ip; external_port = local_port; - if (switch_stun_lookup(&external_ip, &external_port, globals.stun_server, SWITCH_STUN_DEFAULT_PORT, &error, pool) != SWITCH_STATUS_SUCCESS) { + if (switch_stun_lookup(&external_ip, &external_port, globals.stun_server, globals.stun_port, &error, pool) != SWITCH_STATUS_SUCCESS) { switch_log_printf(SWITCH_CHANNEL_LOG, SWITCH_LOG_ERROR, "SignalWire configure failed: stun [%s] lookup error: %s\n", globals.stun_server, error); ks_sleep_ms(4000); goto done; diff --git a/src/mod/applications/mod_spandsp/mod_spandsp.c b/src/mod/applications/mod_spandsp/mod_spandsp.c index 35d0cb585f..3f69b9746a 100644 --- a/src/mod/applications/mod_spandsp/mod_spandsp.c +++ b/src/mod/applications/mod_spandsp/mod_spandsp.c @@ -516,6 +516,7 @@ switch_status_t load_configuration(switch_bool_t reload) spandsp_globals.enable_tep = 0; spandsp_globals.total_sessions = 0; spandsp_globals.verbose = 0; + spandsp_globals.verbose_log_level = SWITCH_LOG_DEBUG; spandsp_globals.use_ecm = 1; spandsp_globals.disable_v17 = 0; spandsp_globals.prepend_string = switch_core_strdup(spandsp_globals.config_pool, "fax"); @@ -591,6 +592,11 @@ switch_status_t load_configuration(switch_bool_t reload) spandsp_globals.verbose = 1; else spandsp_globals.verbose = 0; + } else if (!strcmp(name, "verbose-log-level")) { + switch_log_level_t verbose_log_level = switch_log_str2level(value); + if (verbose_log_level != SWITCH_LOG_INVALID) { + spandsp_globals.verbose_log_level = verbose_log_level; + } } else if (!strcmp(name, "disable-v17")) { if (switch_true(value)) spandsp_globals.disable_v17 = 1; diff --git a/src/mod/applications/mod_spandsp/mod_spandsp.h b/src/mod/applications/mod_spandsp/mod_spandsp.h index 0863831b3c..01f79e254d 100644 --- a/src/mod/applications/mod_spandsp/mod_spandsp.h +++ b/src/mod/applications/mod_spandsp/mod_spandsp.h @@ -70,6 +70,7 @@ struct spandsp_globals { short int use_ecm; short int verbose; + switch_log_level_t verbose_log_level; short int disable_v17; short int enable_tep; short int enable_colour_fax; @@ -106,6 +107,13 @@ typedef enum { FUNCTION_GW } mod_spandsp_fax_application_mode_t; +struct mod_spandsp_log_data { + switch_log_level_t verbose_log_level; + switch_core_session_t *session; + FILE *trace_file; +}; +typedef struct mod_spandsp_log_data mod_spandsp_log_data_t; + /****************************************************************************** * TONE DETECTION WITH CADENCE */ diff --git a/src/mod/applications/mod_spandsp/mod_spandsp_dsp.c b/src/mod/applications/mod_spandsp/mod_spandsp_dsp.c index fca74635e8..836808a48d 100644 --- a/src/mod/applications/mod_spandsp/mod_spandsp_dsp.c +++ b/src/mod/applications/mod_spandsp/mod_spandsp_dsp.c @@ -406,7 +406,12 @@ static switch_bool_t inband_dtmf_callback(switch_media_bug_t *bug, void *user_da switch (type) { case SWITCH_ABC_TYPE_INIT: { pvt->dtmf_detect = dtmf_rx_init(NULL, NULL, NULL); - span_log_set_message_handler(dtmf_rx_get_logging_state(pvt->dtmf_detect), mod_spandsp_log_message, pvt->session); + { + mod_spandsp_log_data_t *log_data = switch_core_session_alloc(pvt->session, sizeof(*log_data)); + log_data->session = pvt->session; + log_data->verbose_log_level = spandsp_globals.verbose_log_level; + span_log_set_message_handler(dtmf_rx_get_logging_state(pvt->dtmf_detect), mod_spandsp_log_message, log_data); + } if (pvt->verbose) { span_log_set_level(dtmf_rx_get_logging_state(pvt->dtmf_detect), SPAN_LOG_SHOW_SEVERITY | SPAN_LOG_SHOW_PROTOCOL | SPAN_LOG_FLOW); } diff --git a/src/mod/applications/mod_spandsp/mod_spandsp_fax.c b/src/mod/applications/mod_spandsp/mod_spandsp_fax.c index 62b7ce99a1..2af4babf08 100644 --- a/src/mod/applications/mod_spandsp/mod_spandsp_fax.c +++ b/src/mod/applications/mod_spandsp/mod_spandsp_fax.c @@ -89,6 +89,7 @@ struct pvt_s { t38_terminal_state_t *t38_state; t38_gateway_state_t *t38_gateway_state; t38_core_state_t *t38_core; + switch_mutex_t *mutex; udptl_state_t *udptl_state; @@ -105,6 +106,8 @@ struct pvt_s { int enable_colour_to_bilevel; int enable_grayscale_to_bilevel; int verbose; + switch_log_level_t verbose_log_level; + FILE *trace_file; int caller; int tx_page_start; @@ -224,7 +227,9 @@ static void *SWITCH_THREAD_FUNC timer_thread_run(switch_thread_t *thread, void * for (pvt = t38_state_list.head; pvt; pvt = pvt->next) { if (pvt->udptl_state && pvt->session && switch_channel_ready(switch_core_session_get_channel(pvt->session))) { + switch_mutex_lock(pvt->mutex); t38_terminal_send_timeout(pvt->t38_state, samples); + switch_mutex_unlock(pvt->mutex); } } @@ -270,7 +275,9 @@ static void counter_increment(void) void mod_spandsp_log_message(void *user_data, int level, const char *msg) { int fs_log_level; - switch_core_session_t *session = (switch_core_session_t *)user_data; + mod_spandsp_log_data_t *log_data = (mod_spandsp_log_data_t *)user_data; + switch_core_session_t *session = log_data ? log_data->session : NULL; + switch_log_level_t verbose_log_level = log_data ? log_data->verbose_log_level : spandsp_globals.verbose_log_level; switch (level) { case SPAN_LOG_NONE: @@ -287,12 +294,15 @@ void mod_spandsp_log_message(void *user_data, int level, const char *msg) case SPAN_LOG_FLOW_2: case SPAN_LOG_FLOW_3: default: /* SPAN_LOG_DEBUG, SPAN_LOG_DEBUG_2, SPAN_LOG_DEBUG_3 */ - fs_log_level = SWITCH_LOG_DEBUG; + fs_log_level = verbose_log_level; break; } if (!zstr(msg)) { - switch_log_printf(SWITCH_CHANNEL_SESSION_LOG(session), fs_log_level, "%s", msg); + switch_log_printf(SWITCH_CHANNEL_SESSION_LOG(session), fs_log_level, "%s", msg); + if (log_data && log_data->trace_file) { + fwrite(msg, strlen(msg) * sizeof(const char), 1, log_data->trace_file); + } } } @@ -307,6 +317,7 @@ static int phase_b_handler(void *user_data, int result) char *fax_document_total_pages = NULL; pvt_t *pvt; switch_event_t *event; + const char *total_pages_str = ""; pvt = (pvt_t *) user_data; switch_assert(pvt); @@ -343,20 +354,30 @@ static int phase_b_handler(void *user_data, int result) switch_channel_set_variable(channel, "fax_remote_model", switch_str_nil(t30_get_rx_model(pvt->t30))); - switch_log_printf(SWITCH_CHANNEL_SESSION_LOG(session), SWITCH_LOG_DEBUG, "=== Negotiation Result =======================================================\n"); - switch_log_printf(SWITCH_CHANNEL_SESSION_LOG(session), SWITCH_LOG_DEBUG, "Remote station id: %s\n", far_ident); - switch_log_printf(SWITCH_CHANNEL_SESSION_LOG(session), SWITCH_LOG_DEBUG, "Local station id: %s\n", local_ident); - switch_log_printf(SWITCH_CHANNEL_SESSION_LOG(session), SWITCH_LOG_DEBUG, "Transfer Rate: %i\n", t30_stats.bit_rate); - switch_log_printf(SWITCH_CHANNEL_SESSION_LOG(session), SWITCH_LOG_DEBUG, "ECM status %s\n", (t30_stats.error_correcting_mode) ? "on" : "off"); - switch_log_printf(SWITCH_CHANNEL_SESSION_LOG(session), SWITCH_LOG_DEBUG, "T38 status %s\n", get_t38_status(pvt->t38_mode)); - switch_log_printf(SWITCH_CHANNEL_SESSION_LOG(session), SWITCH_LOG_DEBUG, "remote country: %s\n", switch_str_nil(t30_get_rx_country(pvt->t30))); - switch_log_printf(SWITCH_CHANNEL_SESSION_LOG(session), SWITCH_LOG_DEBUG, "remote vendor: %s\n", switch_str_nil(t30_get_rx_vendor(pvt->t30))); - switch_log_printf(SWITCH_CHANNEL_SESSION_LOG(session), SWITCH_LOG_DEBUG, "remote model: %s\n", switch_str_nil(t30_get_rx_model(pvt->t30))); if (pvt->app_mode == FUNCTION_TX) { - switch_log_printf(SWITCH_CHANNEL_SESSION_LOG(session), SWITCH_LOG_DEBUG, "Total fax pages: %s\n", fax_document_total_pages); + total_pages_str = switch_core_session_sprintf(session, "Total fax pages: %s\n", fax_document_total_pages); } - - switch_log_printf(SWITCH_CHANNEL_SESSION_LOG(session), SWITCH_LOG_DEBUG, "==============================================================================\n"); + switch_log_printf(SWITCH_CHANNEL_SESSION_LOG(session), SWITCH_LOG_INFO, + "=== Negotiation Result =======================================================\n" + "Remote station id: %s\n" + "Local station id: %s\n" + "Transfer Rate: %i\n" + "ECM status %s\n" + "T38 status %s\n" + "remote country: %s\n" + "remote vendor: %s\n" + "remote model: %s\n" + "%s" + "==============================================================================\n", + far_ident, + local_ident, + t30_stats.bit_rate, + (t30_stats.error_correcting_mode) ? "on" : "off", + get_t38_status(pvt->t38_mode), + switch_str_nil(t30_get_rx_country(pvt->t30)), + switch_str_nil(t30_get_rx_vendor(pvt->t30)), + switch_str_nil(t30_get_rx_model(pvt->t30)), + total_pages_str); switch_channel_execute_on(channel, "execute_on_fax_phase_b"); @@ -396,6 +417,7 @@ static int phase_d_handler(void *user_data, int msg) char *fax_longest_bad_row_run = NULL; char *fax_document_transferred_pages = NULL; char *fax_document_total_pages = NULL; + const char *total_pages_str = ""; switch_core_session_t *session; switch_channel_t *channel; pvt_t *pvt; @@ -468,19 +490,31 @@ static int phase_d_handler(void *user_data, int msg) } } - switch_log_printf(SWITCH_CHANNEL_SESSION_LOG(session), SWITCH_LOG_DEBUG, "==== Page %s===========================================================\n", pvt->app_mode == FUNCTION_TX ? "Sent ====": "Received "); - switch_log_printf(SWITCH_CHANNEL_SESSION_LOG(session), SWITCH_LOG_DEBUG, "Page no = %d\n", (pvt->app_mode == FUNCTION_TX) ? t30_stats.pages_tx : t30_stats.pages_rx); if (pvt->app_mode == FUNCTION_TX) { - switch_log_printf(SWITCH_CHANNEL_SESSION_LOG(session), SWITCH_LOG_DEBUG, "Total fax pages: %s\n", fax_document_total_pages); + total_pages_str = switch_core_session_sprintf(session, "Total fax pages: %s\n", fax_document_total_pages); } - switch_log_printf(SWITCH_CHANNEL_SESSION_LOG(session), SWITCH_LOG_DEBUG, "Image type = %s (%s in the file)\n", t4_image_type_to_str(t30_stats.type), t4_image_type_to_str(t30_stats.image_type)); - switch_log_printf(SWITCH_CHANNEL_SESSION_LOG(session), SWITCH_LOG_DEBUG, "Image size = %d x %d pixels (%d x %d pixels in the file)\n", t30_stats.width, t30_stats.length, t30_stats.image_width, t30_stats.image_length); - switch_log_printf(SWITCH_CHANNEL_SESSION_LOG(session), SWITCH_LOG_DEBUG, "Image resolution = %d/m x %d/m (%d/m x %d/m in the file)\n", t30_stats.x_resolution, t30_stats.y_resolution, t30_stats.image_x_resolution, t30_stats.image_y_resolution); - switch_log_printf(SWITCH_CHANNEL_SESSION_LOG(session), SWITCH_LOG_DEBUG, "Compression = %s (%d)\n", t4_compression_to_str(t30_stats.compression), t30_stats.compression); - switch_log_printf(SWITCH_CHANNEL_SESSION_LOG(session), SWITCH_LOG_DEBUG, "Compressed image size = %d bytes\n", t30_stats.image_size); - switch_log_printf(SWITCH_CHANNEL_SESSION_LOG(session), SWITCH_LOG_DEBUG, "Bad rows = %d\n", t30_stats.bad_rows); - switch_log_printf(SWITCH_CHANNEL_SESSION_LOG(session), SWITCH_LOG_DEBUG, "Longest bad row run = %d\n", t30_stats.longest_bad_row_run); - switch_log_printf(SWITCH_CHANNEL_SESSION_LOG(session), SWITCH_LOG_DEBUG, "==============================================================================\n"); + switch_log_printf(SWITCH_CHANNEL_SESSION_LOG(session), SWITCH_LOG_INFO, + "==== Page %s===========================================================\n" + "Page no = %d\n" + "%s" + "Image type = %s (%s in the file)\n" + "Image size = %d x %d pixels (%d x %d pixels in the file)\n" + "Image resolution = %d/m x %d/m (%d/m x %d/m in the file)\n" + "Compression = %s (%d)\n" + "Compressed image size = %d bytes\n" + "Bad rows = %d\n" + "Longest bad row run = %d\n" + "==============================================================================\n", + pvt->app_mode == FUNCTION_TX ? "Sent ====": "Received ", + (pvt->app_mode == FUNCTION_TX) ? t30_stats.pages_tx : t30_stats.pages_rx, + total_pages_str, + t4_image_type_to_str(t30_stats.type), t4_image_type_to_str(t30_stats.image_type), + t30_stats.width, t30_stats.length, t30_stats.image_width, t30_stats.image_length, + t30_stats.x_resolution, t30_stats.y_resolution, t30_stats.image_x_resolution, t30_stats.image_y_resolution, + t4_compression_to_str(t30_stats.compression), t30_stats.compression, + t30_stats.image_size, + t30_stats.bad_rows, + t30_stats.longest_bad_row_run); switch_channel_execute_on(channel, "execute_on_fax_phase_d"); @@ -528,6 +562,7 @@ static void phase_e_handler(void *user_data, int result) switch_event_t *event; const char *var; char *expanded; + const char *fax_result_str = ""; pvt = (pvt_t *) user_data; switch_assert(pvt); @@ -542,38 +577,49 @@ static void phase_e_handler(void *user_data, int result) local_ident = switch_str_nil(t30_get_tx_ident(pvt->t30)); far_ident = switch_str_nil(t30_get_rx_ident(pvt->t30)); - switch_log_printf(SWITCH_CHANNEL_SESSION_LOG(session), SWITCH_LOG_DEBUG, "==============================================================================\n"); if (result == T30_ERR_OK) { if (pvt->app_mode == FUNCTION_TX) { - switch_log_printf(SWITCH_CHANNEL_SESSION_LOG(session), SWITCH_LOG_DEBUG, "Fax successfully sent.\n"); + fax_result_str = switch_core_session_sprintf(session, "Fax successfully sent.\n"); } else if (pvt->app_mode == FUNCTION_RX) { - switch_log_printf(SWITCH_CHANNEL_SESSION_LOG(session), SWITCH_LOG_DEBUG, "Fax successfully received.\n"); + fax_result_str = switch_core_session_sprintf(session, "Fax successfully received.\n"); } else { - switch_log_printf(SWITCH_CHANNEL_SESSION_LOG(session), SWITCH_LOG_DEBUG, "Fax successfully managed. How ?\n"); + fax_result_str = switch_core_session_sprintf(session, "Fax successfully managed. How ?\n"); } switch_channel_set_variable(channel, "fax_success", "1"); } else { - switch_log_printf(SWITCH_CHANNEL_SESSION_LOG(session), SWITCH_LOG_DEBUG, "Fax processing not successful - result (%d) %s.\n", result, + fax_result_str = switch_core_session_sprintf(session, "Fax processing not successful - result (%d) %s.\n", result, t30_completion_code_to_str(result)); switch_channel_set_variable(channel, "fax_success", "0"); } - switch_log_printf(SWITCH_CHANNEL_SESSION_LOG(session), SWITCH_LOG_DEBUG, "Remote station id: %s\n", far_ident); - switch_log_printf(SWITCH_CHANNEL_SESSION_LOG(session), SWITCH_LOG_DEBUG, "Local station id: %s\n", local_ident); - switch_log_printf(SWITCH_CHANNEL_SESSION_LOG(session), SWITCH_LOG_DEBUG, "Pages transferred: %i\n", - pvt->app_mode == FUNCTION_TX ? t.pages_tx : t.pages_rx); - switch_log_printf(SWITCH_CHANNEL_SESSION_LOG(session), SWITCH_LOG_DEBUG, "Total fax pages: %i\n", t.pages_in_file); - switch_log_printf(SWITCH_CHANNEL_SESSION_LOG(session), SWITCH_LOG_DEBUG, "Image resolution: %ix%i\n", t.x_resolution, t.y_resolution); - switch_log_printf(SWITCH_CHANNEL_SESSION_LOG(session), SWITCH_LOG_DEBUG, "Transfer Rate: %i\n", t.bit_rate); - - switch_log_printf(SWITCH_CHANNEL_SESSION_LOG(session), SWITCH_LOG_DEBUG, "ECM status %s\n", (t.error_correcting_mode) ? "on" : "off"); - switch_log_printf(SWITCH_CHANNEL_SESSION_LOG(session), SWITCH_LOG_DEBUG, "T38 status %s\n", get_t38_status(pvt->t38_mode)); - switch_log_printf(SWITCH_CHANNEL_SESSION_LOG(session), SWITCH_LOG_DEBUG, "remote country: %s\n", switch_str_nil(t30_get_rx_country(pvt->t30))); - switch_log_printf(SWITCH_CHANNEL_SESSION_LOG(session), SWITCH_LOG_DEBUG, "remote vendor: %s\n", switch_str_nil(t30_get_rx_vendor(pvt->t30))); - switch_log_printf(SWITCH_CHANNEL_SESSION_LOG(session), SWITCH_LOG_DEBUG, "remote model: %s\n", switch_str_nil(t30_get_rx_model(pvt->t30))); - - switch_log_printf(SWITCH_CHANNEL_SESSION_LOG(session), SWITCH_LOG_DEBUG, "==============================================================================\n"); + switch_log_printf(SWITCH_CHANNEL_SESSION_LOG(session), SWITCH_LOG_INFO, + "==============================================================================\n" + "%s" + "Remote station id: %s\n" + "Local station id: %s\n" + "Pages transferred: %i\n" + "Total fax pages: %i\n" + "Image resolution: %ix%i\n" + "Transfer Rate: %i\n" + "ECM status %s\n" + "T38 status %s\n" + "remote country: %s\n" + "remote vendor: %s\n" + "remote model: %s\n" + "==============================================================================\n", + fax_result_str, + far_ident, + local_ident, + pvt->app_mode == FUNCTION_TX ? t.pages_tx : t.pages_rx, + t.pages_in_file, + t.x_resolution, t.y_resolution, + t.bit_rate, + (t.error_correcting_mode) ? "on" : "off", + get_t38_status(pvt->t38_mode), + switch_str_nil(t30_get_rx_country(pvt->t30)), + switch_str_nil(t30_get_rx_vendor(pvt->t30)), + switch_str_nil(t30_get_rx_model(pvt->t30))); /* Set our channel variables, variables are also used in event @@ -772,8 +818,14 @@ static switch_status_t spanfax_init(pvt_t *pvt, transport_mode_t trans_mode) fax_set_transmit_on_idle(fax, TRUE); - span_log_set_message_handler(fax_get_logging_state(fax), mod_spandsp_log_message, pvt->session); - span_log_set_message_handler(t30_get_logging_state(t30), mod_spandsp_log_message, pvt->session); + { + mod_spandsp_log_data_t *log_data = switch_core_session_alloc(pvt->session, sizeof(*log_data)); + log_data->session = pvt->session; + log_data->verbose_log_level = pvt->verbose_log_level; + log_data->trace_file = pvt->trace_file; + span_log_set_message_handler(fax_get_logging_state(fax), mod_spandsp_log_message, log_data); + span_log_set_message_handler(t30_get_logging_state(t30), mod_spandsp_log_message, log_data); + } if (pvt->verbose) { span_log_set_level(fax_get_logging_state(fax), SPAN_LOG_SHOW_SEVERITY | SPAN_LOG_SHOW_PROTOCOL | SPAN_LOG_FLOW); @@ -783,7 +835,6 @@ static switch_status_t spanfax_init(pvt_t *pvt, transport_mode_t trans_mode) case T38_MODE: { switch_core_session_message_t msg = { 0 }; - if (pvt->t38_state == NULL) { pvt->t38_state = (t38_terminal_state_t *) switch_core_session_alloc(pvt->session, sizeof(t38_terminal_state_t)); } @@ -822,14 +873,15 @@ static switch_status_t spanfax_init(pvt_t *pvt, transport_mode_t trans_mode) msg.message_id = SWITCH_MESSAGE_INDICATE_UDPTL_MODE; switch_core_session_receive_message(pvt->session, &msg); - /* add to timer thread processing */ - if (!add_pvt(pvt)) { - switch_channel_hangup(channel, SWITCH_CAUSE_DESTINATION_OUT_OF_ORDER); + { + mod_spandsp_log_data_t *log_data = switch_core_session_alloc(pvt->session, sizeof(*log_data)); + log_data->session = pvt->session; + log_data->verbose_log_level = pvt->verbose_log_level; + log_data->trace_file = pvt->trace_file; + span_log_set_message_handler(t38_terminal_get_logging_state(t38), mod_spandsp_log_message, log_data); + span_log_set_message_handler(t30_get_logging_state(t30), mod_spandsp_log_message, log_data); } - span_log_set_message_handler(t38_terminal_get_logging_state(t38), mod_spandsp_log_message, pvt->session); - span_log_set_message_handler(t30_get_logging_state(t30), mod_spandsp_log_message, pvt->session); - if (pvt->verbose) { span_log_set_level(t38_terminal_get_logging_state(t38), SPAN_LOG_SHOW_SEVERITY | SPAN_LOG_SHOW_PROTOCOL | SPAN_LOG_FLOW); span_log_set_level(t30_get_logging_state(t30), SPAN_LOG_SHOW_SEVERITY | SPAN_LOG_SHOW_PROTOCOL | SPAN_LOG_FLOW); @@ -877,8 +929,14 @@ static switch_status_t spanfax_init(pvt_t *pvt, transport_mode_t trans_mode) t38_gateway_set_ecm_capability(pvt->t38_gateway_state, pvt->use_ecm); switch_channel_set_variable(channel, "fax_ecm_requested", pvt->use_ecm ? "true" : "false"); - span_log_set_message_handler(t38_gateway_get_logging_state(pvt->t38_gateway_state), mod_spandsp_log_message, pvt->session); - span_log_set_message_handler(t38_core_get_logging_state(pvt->t38_core), mod_spandsp_log_message, pvt->session); + { + mod_spandsp_log_data_t *log_data = switch_core_session_alloc(pvt->session, sizeof(*log_data)); + log_data->session = pvt->session; + log_data->verbose_log_level = pvt->verbose_log_level; + log_data->trace_file = pvt->trace_file; + span_log_set_message_handler(t38_gateway_get_logging_state(pvt->t38_gateway_state), mod_spandsp_log_message, log_data); + span_log_set_message_handler(t38_core_get_logging_state(pvt->t38_core), mod_spandsp_log_message, log_data); + } if (pvt->verbose) { span_log_set_level(t38_gateway_get_logging_state(pvt->t38_gateway_state), SPAN_LOG_SHOW_SEVERITY | SPAN_LOG_SHOW_PROTOCOL | SPAN_LOG_FLOW); @@ -1020,6 +1078,12 @@ static switch_status_t spanfax_destroy(pvt_t *pvt) if (pvt->udptl_state) { udptl_release(pvt->udptl_state); } + + if (pvt->trace_file) { + fclose(pvt->trace_file); + pvt->trace_file = NULL; + } + return SWITCH_STATUS_SUCCESS; } @@ -1092,20 +1156,33 @@ static t38_mode_t negotiate_t38(pvt_t *pvt) pvt->t38_mode = T38_MODE_NEGOTIATED; switch_channel_set_app_flag_key("T38", channel, CF_APP_T38_NEGOTIATED); - switch_log_printf(SWITCH_CHANNEL_SESSION_LOG(session), SWITCH_LOG_DEBUG, "T38 SDP Origin = %s\n", t38_options->sdp_o_line); - switch_log_printf(SWITCH_CHANNEL_SESSION_LOG(session), SWITCH_LOG_DEBUG, "T38FaxVersion = %d\n", t38_options->T38FaxVersion); - switch_log_printf(SWITCH_CHANNEL_SESSION_LOG(session), SWITCH_LOG_DEBUG, "T38MaxBitRate = %d\n", t38_options->T38MaxBitRate); - switch_log_printf(SWITCH_CHANNEL_SESSION_LOG(session), SWITCH_LOG_DEBUG, "T38FaxFillBitRemoval = %d\n", t38_options->T38FaxFillBitRemoval); - switch_log_printf(SWITCH_CHANNEL_SESSION_LOG(session), SWITCH_LOG_DEBUG, "T38FaxTranscodingMMR = %d\n", t38_options->T38FaxTranscodingMMR); - switch_log_printf(SWITCH_CHANNEL_SESSION_LOG(session), SWITCH_LOG_DEBUG, "T38FaxTranscodingJBIG = %d\n", t38_options->T38FaxTranscodingJBIG); - switch_log_printf(SWITCH_CHANNEL_SESSION_LOG(session), SWITCH_LOG_DEBUG, "T38FaxRateManagement = '%s'\n", t38_options->T38FaxRateManagement); - switch_log_printf(SWITCH_CHANNEL_SESSION_LOG(session), SWITCH_LOG_DEBUG, "T38FaxMaxBuffer = %d\n", t38_options->T38FaxMaxBuffer); - switch_log_printf(SWITCH_CHANNEL_SESSION_LOG(session), SWITCH_LOG_DEBUG, "T38FaxMaxDatagram = %d\n", t38_options->T38FaxMaxDatagram); - switch_log_printf(SWITCH_CHANNEL_SESSION_LOG(session), SWITCH_LOG_DEBUG, "T38FaxUdpEC = '%s'\n", t38_options->T38FaxUdpEC); - switch_log_printf(SWITCH_CHANNEL_SESSION_LOG(session), SWITCH_LOG_DEBUG, "T38VendorInfo = '%s'\n", switch_str_nil(t38_options->T38VendorInfo)); - switch_log_printf(SWITCH_CHANNEL_SESSION_LOG(session), SWITCH_LOG_DEBUG, "ip = '%s'\n", - t38_options->remote_ip ? t38_options->remote_ip : "Not specified"); - switch_log_printf(SWITCH_CHANNEL_SESSION_LOG(session), SWITCH_LOG_DEBUG, "port = %d\n", t38_options->remote_port); + switch_log_printf(SWITCH_CHANNEL_SESSION_LOG(session), SWITCH_LOG_INFO, + "T38 SDP Origin = %s\n" + "T38FaxVersion = %d\n" + "T38MaxBitRate = %d\n" + "T38FaxFillBitRemoval = %d\n" + "T38FaxTranscodingMMR = %d\n" + "T38FaxTranscodingJBIG = %d\n" + "T38FaxRateManagement = '%s'\n" + "T38FaxMaxBuffer = %d\n" + "T38FaxMaxDatagram = %d\n" + "T38FaxUdpEC = '%s'\n" + "T38VendorInfo = '%s'\n" + "ip = '%s'\n" + "port = %d\n", + t38_options->sdp_o_line, + t38_options->T38FaxVersion, + t38_options->T38MaxBitRate, + t38_options->T38FaxFillBitRemoval, + t38_options->T38FaxTranscodingMMR, + t38_options->T38FaxTranscodingJBIG, + t38_options->T38FaxRateManagement, + t38_options->T38FaxMaxBuffer, + t38_options->T38FaxMaxDatagram, + t38_options->T38FaxUdpEC, + switch_str_nil(t38_options->T38VendorInfo), + t38_options->remote_ip ? t38_options->remote_ip : "Not specified", + t38_options->remote_port); /* Time to practice our negotiating skills, by editing the t38_options */ @@ -1319,6 +1396,23 @@ static pvt_t *pvt_init(switch_core_session_t *session, mod_spandsp_fax_applicati pvt->verbose = spandsp_globals.verbose; } + pvt->verbose_log_level = spandsp_globals.verbose_log_level; + if ((tmp = switch_channel_get_variable(channel, "fax_verbose_log_level"))) { + switch_log_level_t verbose_log_level = switch_log_str2level(tmp); + if (verbose_log_level != SWITCH_LOG_INVALID) { + pvt->verbose_log_level = verbose_log_level; + } + } + + if ((tmp = switch_channel_get_variable(channel, "fax_trace_dir"))) { + const char *trace_filename = switch_core_session_sprintf(session, "%s"SWITCH_PATH_SEPARATOR"fax-%s.log", tmp, switch_core_session_get_uuid(session)); + switch_dir_make_recursive(tmp, SWITCH_DEFAULT_DIR_PERMS, switch_core_session_get_pool(session)); + pvt->trace_file = fopen(trace_filename, "w"); + if (pvt->trace_file) { + switch_channel_set_variable(channel, "fax_trace_file", trace_filename); + } + } + if ((tmp = switch_channel_get_variable(channel, "fax_force_caller"))) { if (switch_true(tmp)) { pvt->caller = 1; @@ -1385,6 +1479,8 @@ static pvt_t *pvt_init(switch_core_session_t *session, mod_spandsp_fax_applicati } } + switch_mutex_init(&pvt->mutex, SWITCH_MUTEX_NESTED, switch_core_session_get_pool(session)); + return pvt; } @@ -1592,8 +1688,17 @@ void mod_spandsp_fax_process_fax(switch_core_session_t *session, const char *dat switch_core_session_message_t msg = { 0 }; pvt->t38_mode = T38_MODE_NEGOTIATED; switch_channel_set_app_flag_key("T38", channel, CF_APP_T38_NEGOTIATED); - spanfax_init(pvt, T38_MODE); - configure_t38(pvt); + if (spanfax_init(pvt, T38_MODE) == SWITCH_STATUS_SUCCESS) { + configure_t38(pvt); + /* add to timer thread processing */ + if (!add_pvt(pvt)) { + switch_channel_hangup(channel, SWITCH_CAUSE_DESTINATION_OUT_OF_ORDER); + } + } else { + switch_log_printf(SWITCH_CHANNEL_SESSION_LOG(session), SWITCH_LOG_ERROR, "Cannot initialize Fax engine for T.38\n"); + switch_channel_set_variable(channel, SWITCH_CURRENT_APPLICATION_RESPONSE_VARIABLE, "Cannot initialize Fax engine for T.38"); + goto done; + } /* This will change the rtp stack to udptl mode */ msg.from = __FILE__; @@ -1616,7 +1721,16 @@ void mod_spandsp_fax_process_fax(switch_core_session_t *session, const char *dat if (negotiate_t38(pvt) == T38_MODE_NEGOTIATED) { /* is is safe to call this again, it was already called above in AUDIO_MODE */ /* but this is the only way to set up the t38 stuff */ - spanfax_init(pvt, T38_MODE); + if (spanfax_init(pvt, T38_MODE) == SWITCH_STATUS_SUCCESS) { + /* add to timer thread processing */ + if (!add_pvt(pvt)) { + switch_channel_hangup(channel, SWITCH_CAUSE_DESTINATION_OUT_OF_ORDER); + } + } else { + switch_log_printf(SWITCH_CHANNEL_SESSION_LOG(session), SWITCH_LOG_ERROR, "Cannot initialize Fax engine for T.38\n"); + switch_channel_set_variable(channel, SWITCH_CURRENT_APPLICATION_RESPONSE_VARIABLE, "Cannot initialize Fax engine for T.38"); + goto done; + } continue; } } @@ -1634,7 +1748,9 @@ void mod_spandsp_fax_process_fax(switch_core_session_t *session, const char *dat /* now we know we can cast frame->packet to a udptl structure */ //switch_log_printf(SWITCH_CHANNEL_SESSION_LOG(session), SWITCH_LOG_ERROR, "READ %d udptl bytes\n", read_frame->packetlen); + switch_mutex_lock(pvt->mutex); udptl_rx_packet(pvt->udptl_state, read_frame->packet, read_frame->packetlen); + switch_mutex_unlock(pvt->mutex); } } continue; @@ -1642,16 +1758,19 @@ void mod_spandsp_fax_process_fax(switch_core_session_t *session, const char *dat break; } + switch_mutex_lock(pvt->mutex); if (switch_test_flag(read_frame, SFF_CNG)) { /* We have no real signal data for the FAX software, but we have a space in time if we have a CNG indication. Do a fill-in operation in the FAX machine, to keep things rolling along. */ if (fax_rx_fillin(pvt->fax_state, read_impl.samples_per_packet)) { + switch_mutex_unlock(pvt->mutex); switch_log_printf(SWITCH_CHANNEL_SESSION_LOG(session), SWITCH_LOG_ERROR, "fax_rx_fillin reported an error\n"); continue; } } else { /* Pass the new incoming audio frame to the fax_rx function */ if (fax_rx(pvt->fax_state, (int16_t *) read_frame->data, read_frame->samples)) { + switch_mutex_unlock(pvt->mutex); switch_log_printf(SWITCH_CHANNEL_SESSION_LOG(session), SWITCH_LOG_ERROR, "fax_rx reported an error\n"); switch_channel_set_variable(channel, SWITCH_CURRENT_APPLICATION_RESPONSE_VARIABLE, "fax_rx reported an error"); goto done; @@ -1659,10 +1778,12 @@ void mod_spandsp_fax_process_fax(switch_core_session_t *session, const char *dat } if ((tx = fax_tx(pvt->fax_state, buf, write_codec.implementation->samples_per_packet)) < 0) { + switch_mutex_unlock(pvt->mutex); switch_log_printf(SWITCH_CHANNEL_SESSION_LOG(session), SWITCH_LOG_ERROR, "fax_tx reported an error\n"); switch_channel_set_variable(channel, SWITCH_CURRENT_APPLICATION_RESPONSE_VARIABLE, "fax_tx reported an error"); goto done; } + switch_mutex_unlock(pvt->mutex); if (!tx) { /* switch_log_printf(SWITCH_CHANNEL_SESSION_LOG(session), SWITCH_LOG_DEBUG, "No audio samples to send\n"); */ @@ -2141,7 +2262,7 @@ switch_bool_t t38_gateway_start(switch_core_session_t *session, const char *app, switch_channel_set_variable(peer ? channel : other_channel, "t38_gateway_format", "audio"); - switch_log_printf(SWITCH_CHANNEL_SESSION_LOG(session), SWITCH_LOG_DEBUG, "%s starting gateway mode to %s\n", + switch_log_printf(SWITCH_CHANNEL_SESSION_LOG(session), SWITCH_LOG_INFO, "%s starting gateway mode to %s\n", switch_channel_get_name(peer ? channel : other_channel), switch_channel_get_name(peer ? other_channel : channel)); @@ -2274,7 +2395,7 @@ static switch_bool_t tone_detect_callback(switch_media_bug_t *bug, void *user_da if (cont->hits) { switch_event_t *event; - switch_log_printf(SWITCH_CHANNEL_SESSION_LOG(switch_core_media_bug_get_session(bug)), SWITCH_LOG_DEBUG, + switch_log_printf(SWITCH_CHANNEL_SESSION_LOG(switch_core_media_bug_get_session(bug)), SWITCH_LOG_INFO, "Fax Tone Detected. [%s][%s]\n", cont->app, switch_str_nil(cont->data)); if (cont->callback) { diff --git a/src/mod/applications/mod_spandsp/mod_spandsp_modem.c b/src/mod/applications/mod_spandsp/mod_spandsp_modem.c index 5613b4aa4c..560a78be44 100644 --- a/src/mod/applications/mod_spandsp/mod_spandsp_modem.c +++ b/src/mod/applications/mod_spandsp/mod_spandsp_modem.c @@ -279,11 +279,11 @@ switch_status_t modem_init(modem_t *modem, modem_control_handler_t control_handl modem->stty = ptsname(modem->master); if (modem->stty == NULL) { switch_log_printf(SWITCH_CHANNEL_LOG, SWITCH_LOG_ERROR, "Fatal error: failed to obtain slave pty filename\n"); - } - - modem->slave = open(modem->stty, O_RDWR); - if (modem->slave < 0) { - switch_log_printf(SWITCH_CHANNEL_LOG, SWITCH_LOG_ERROR, "Fatal error: failed to open slave pty %s\n", modem->stty); + } else { + modem->slave = open(modem->stty, O_RDWR); + if (modem->slave < 0) { + switch_log_printf(SWITCH_CHANNEL_LOG, SWITCH_LOG_ERROR, "Fatal error: failed to open slave pty %s\n", modem->stty); + } } #endif diff --git a/src/mod/applications/mod_spandsp/udptl.c b/src/mod/applications/mod_spandsp/udptl.c index 50a996903a..aa82f953d0 100644 --- a/src/mod/applications/mod_spandsp/udptl.c +++ b/src/mod/applications/mod_spandsp/udptl.c @@ -296,7 +296,7 @@ int udptl_rx_packet(udptl_state_t *s, const uint8_t buf[], int len) return -1; /* Save the new FEC data */ - if (s->rx[x].fec_len[i]) + if (s->rx[x].fec_len[i] && data) memcpy(s->rx[x].fec[i], data, s->rx[x].fec_len[i]); #if 0 switch_log_printf(SWITCH_CHANNEL_LOG, SWITCH_LOG_DEBUG, "FEC: "); diff --git a/src/mod/applications/mod_test/mod_test.c b/src/mod/applications/mod_test/mod_test.c index 9791d7a611..55729548f7 100644 --- a/src/mod/applications/mod_test/mod_test.c +++ b/src/mod/applications/mod_test/mod_test.c @@ -1,6 +1,6 @@ /* * FreeSWITCH Modular Media Switching Software Library / Soft-Switch Application - * Copyright (C) 2005-2020, Anthony Minessale II + * Copyright (C) 2005-2021, Anthony Minessale II * * Version: MPL 1.1 * @@ -41,6 +41,7 @@ SWITCH_MODULE_DEFINITION(mod_test, mod_test_load, mod_test_shutdown, mod_test_ru typedef struct { char *text; int samples; + const char *channel_uuid; } test_tts_t; typedef enum { @@ -68,6 +69,7 @@ typedef struct { char *grammar; char *channel_uuid; switch_vad_t *vad; + int partial; } test_asr_t; @@ -268,12 +270,17 @@ static switch_status_t test_asr_get_results(switch_asr_handle_t *ah, char **resu } if (switch_test_flag(context, ASRFLAG_RESULT)) { + int is_partial = context->partial-- > 0 ? 1 : 0; *resultstr = switch_mprintf("{\"grammar\": \"%s\", \"text\": \"%s\", \"confidence\": %f}", context->grammar, context->result_text, context->result_confidence); - switch_log_printf(SWITCH_CHANNEL_UUID_LOG(context->channel_uuid), SWITCH_LOG_ERROR, "Result: %s\n", *resultstr); + switch_log_printf(SWITCH_CHANNEL_UUID_LOG(context->channel_uuid), SWITCH_LOG_NOTICE, "%sResult: %s\n", is_partial ? "Partial " : "Final ", *resultstr); - status = SWITCH_STATUS_SUCCESS; + if (is_partial) { + status = SWITCH_STATUS_MORE_DATA; + } else { + status = SWITCH_STATUS_SUCCESS; + } } else if (switch_test_flag(context, ASRFLAG_NOINPUT_TIMEOUT)) { switch_log_printf(SWITCH_CHANNEL_UUID_LOG(context->channel_uuid), SWITCH_LOG_DEBUG, "Result: NO INPUT\n"); @@ -361,6 +368,9 @@ static void test_asr_text_param(switch_asr_handle_t *ah, char *param, const char } else if (!strcasecmp("confidence", param) && fval >= 0.0) { context->result_confidence = fval; switch_log_printf(SWITCH_CHANNEL_UUID_LOG(context->channel_uuid), SWITCH_LOG_DEBUG, "confidence = %f\n", fval); + } else if (!strcasecmp("partial", param) && switch_true(val)) { + context->partial = 3; + switch_log_printf(SWITCH_CHANNEL_UUID_LOG(context->channel_uuid), SWITCH_LOG_DEBUG, "partial = %d\n", context->partial); } } } @@ -384,6 +394,10 @@ static switch_status_t test_speech_feed_tts(switch_speech_handle_t *sh, char *te { test_tts_t *context = (test_tts_t *)sh->private_info; + if (switch_true(switch_core_get_variable("mod_test_tts_must_have_channel_uuid")) && zstr(context->channel_uuid)) { + return SWITCH_STATUS_FALSE; + } + if (!zstr(text)) { char *p = strstr(text, "silence://"); @@ -422,6 +436,13 @@ static void test_speech_flush_tts(switch_speech_handle_t *sh) static void test_speech_text_param_tts(switch_speech_handle_t *sh, char *param, const char *val) { + test_tts_t *context = (test_tts_t *)sh->private_info; + if (!zstr(param) && !zstr(val)) { + if (!strcasecmp("channel-uuid", param)) { + context->channel_uuid = switch_core_strdup(sh->memory_pool, val); + switch_log_printf(SWITCH_CHANNEL_UUID_LOG(context->channel_uuid), SWITCH_LOG_DEBUG, "channel-uuid = %s\n", val); + } + } } static void test_speech_numeric_param_tts(switch_speech_handle_t *sh, char *param, int val) diff --git a/src/mod/applications/mod_valet_parking/mod_valet_parking.c b/src/mod/applications/mod_valet_parking/mod_valet_parking.c index 0c95c16265..c304cad824 100644 --- a/src/mod/applications/mod_valet_parking/mod_valet_parking.c +++ b/src/mod/applications/mod_valet_parking/mod_valet_parking.c @@ -86,6 +86,34 @@ static switch_status_t valet_on_dtmf(switch_core_session_t *session, void *input case SWITCH_INPUT_TYPE_DTMF: { switch_dtmf_t *dtmf = (switch_dtmf_t *) input; + switch_channel_t *channel = switch_core_session_get_channel(session); + switch_dtmf_t *exit_key_pvt = (switch_dtmf_t *) switch_channel_get_private(channel, "_orbit_exit_key_"); + + if (exit_key_pvt && dtmf->digit == exit_key_pvt->digit) { + const char *dp; + const char *exten; + const char *context; + + switch_log_printf(SWITCH_CHANNEL_LOG, SWITCH_LOG_ERROR, "valet_on_dtmf() - digit pressed '%d' matched valet_parking_orbit_exit_key '%d'\n", dtmf->digit, exit_key_pvt->digit); + + dp = switch_channel_get_variable(channel, "valet_parking_orbit_dialplan"); + if (zstr(dp)) { + dp = switch_channel_get_variable(channel, "XML"); + } + + context = switch_channel_get_variable(channel, "valet_parking_orbit_context"); + if (zstr(context)) { + context = switch_channel_get_variable(channel, "context"); + } + + exten = switch_channel_get_variable(channel, "valet_parking_orbit_exten"); + if (!zstr(exten)) { + switch_log_printf(SWITCH_CHANNEL_LOG, SWITCH_LOG_ERROR, "valet_on_dtmf() - transferring session to '%s %s %s'\n", exten, dp, context); + switch_ivr_session_transfer(session, exten, dp, context); + } + + return SWITCH_STATUS_BREAK; + } if (dtmf->digit == '#') { return SWITCH_STATUS_BREAK; @@ -433,8 +461,8 @@ SWITCH_STANDARD_APP(valet_parking_function) char *dest; int in = -1; - const char *timeout, *orbit_exten, *orbit_dialplan, *orbit_context; - char *timeout_str = "", *orbit_exten_str = "", *orbit_dialplan_str = "", *orbit_context_str = ""; + const char *timeout, *orbit_exten, *orbit_dialplan, *orbit_context, *orbit_exit_key; + char *timeout_str = "", *orbit_exten_str = "", *orbit_dialplan_str = "", *orbit_context_str = "", *orbit_exit_key_str = ""; lot = valet_find_lot(lot_name, SWITCH_TRUE); switch_assert(lot); @@ -606,16 +634,23 @@ SWITCH_STANDARD_APP(valet_parking_function) orbit_context_str = switch_core_session_sprintf(session, "set:valet_parking_orbit_context=%s,", orbit_context); } + if ((orbit_exit_key = switch_channel_get_variable(channel, "valet_parking_orbit_exit_key"))) { + orbit_exit_key_str = switch_core_session_sprintf(session, "set:valet_parking_orbit_exit_key=%s,", orbit_exit_key); + + switch_channel_set_private(channel, "_orbit_exit_key_", orbit_exit_key); + } + if ((timeout = switch_channel_get_variable(channel, "valet_parking_timeout"))) { timeout_str = switch_core_session_sprintf(session, "set:valet_parking_timeout=%s,", timeout); } - dest = switch_core_session_sprintf(session, "%s%s%s%s" + dest = switch_core_session_sprintf(session, "%s%s%s%s%s" "set:valet_ticket=%s,set:valet_hold_music='%s',sleep:1000,valet_park:%s %s", timeout_str, orbit_exten_str, orbit_dialplan_str, orbit_context_str, + orbit_exit_key_str, token->uuid, music, lot_name, ext); switch_channel_set_variable(channel, "inline_destination", dest); diff --git a/src/mod/applications/mod_video_filter/mod_video_filter.c b/src/mod/applications/mod_video_filter/mod_video_filter.c index 613f8d9195..2f4d5d5bf7 100644 --- a/src/mod/applications/mod_video_filter/mod_video_filter.c +++ b/src/mod/applications/mod_video_filter/mod_video_filter.c @@ -74,6 +74,7 @@ typedef struct video_replace_context_s { switch_image_t *rp_img; switch_file_handle_t vfh; switch_core_session_t *session; + int sound; } video_replace_context_t; @@ -227,7 +228,6 @@ static void parse_params(chromakey_context_t *context, int start, int argc, char if (n > 2 && argv[i]) { if (context->child_bug) { - printf("WTF CLOSE IT\n"); switch_core_media_bug_close(&context->child_bug, SWITCH_TRUE); context->child_uuid = NULL; } @@ -575,6 +575,7 @@ static switch_status_t video_thread_callback(switch_core_session_t *session, swi if (context->vfh.params) { const char *loopstr = switch_event_get_header(context->vfh.params, "loop"); + if (switch_true(loopstr)) { uint32_t pos = 0; switch_core_file_seek(&context->vfh, &pos, 0, SEEK_SET); @@ -612,7 +613,6 @@ static switch_status_t video_thread_callback(switch_core_session_t *session, swi status = switch_core_file_read_video(&context->fg_vfh, &file_frame, SVR_FLUSH); switch_core_file_command(&context->fg_vfh, SCFC_FLUSH_AUDIO); - if (status != SWITCH_STATUS_SUCCESS && status != SWITCH_STATUS_BREAK) { int close = 1; @@ -840,41 +840,51 @@ static switch_status_t video_replace_thread_callback(switch_core_session_t *sess if (switch_test_flag(&context->vfh, SWITCH_FILE_OPEN)) { switch_status_t status = SWITCH_STATUS_FALSE; - if (type == SWITCH_ABC_TYPE_READ_VIDEO_PING || (context->vfh.params && switch_true(switch_event_get_header(context->vfh.params, "scale")))) { - context->vfh.mm.scale_w = frame->img->d_w; - context->vfh.mm.scale_h = frame->img->d_h; - } + //if (type == SWITCH_ABC_TYPE_READ_VIDEO_PING || (context->vfh.params && switch_true(switch_event_get_header(context->vfh.params, "scale")))) { + //context->vfh.mm.scale_w = frame->img->d_w; + //context->vfh.mm.scale_h = frame->img->d_h; + //} status = switch_core_file_read_video(&context->vfh, &file_frame, SVR_FLUSH); - switch_core_file_command(&context->vfh, SCFC_FLUSH_AUDIO); - + if (!context->sound) { + switch_core_file_command(&context->vfh, SCFC_FLUSH_AUDIO); + } + if (status != SWITCH_STATUS_SUCCESS && status != SWITCH_STATUS_BREAK) { int close = 1; - + if (context->vfh.params) { const char *loopstr = switch_event_get_header(context->vfh.params, "loop"); if (switch_true(loopstr)) { uint32_t pos = 0; - if (switch_core_file_seek(&context->vfh, &pos, 0, SEEK_SET) == SWITCH_STATUS_SUCCESS) close = 0; + switch_core_file_seek(&context->vfh, &pos, 0, SEEK_SET); + close = 0; } } if (close) { switch_core_file_close(&context->vfh); + switch_core_session_request_video_refresh(session); } } if (file_frame.img) { switch_img_free(&(context->rp_img)); - context->rp_img = file_frame.img; + + if (frame->img && (frame->img->d_w != file_frame.img->d_w || frame->img->d_h != file_frame.img->d_h)) { + switch_img_letterbox(file_frame.img, &context->rp_img, frame->img->d_w, frame->img->d_h, "#0000000"); + switch_img_free(&file_frame.img); + } else { + context->rp_img = file_frame.img; + } } if (context->rp_img) { if (context->rp_img->d_w != frame->img->d_w || context->rp_img->d_h != frame->img->d_h ) { frame->img = NULL; } - + switch_img_copy(context->rp_img, &frame->img); } } @@ -891,10 +901,17 @@ static switch_bool_t video_replace_bug_callback(switch_media_bug_t *bug, void *u switch (type) { case SWITCH_ABC_TYPE_INIT: { + switch_core_session_request_video_refresh(session); + switch_channel_set_flag(channel, CF_VIDEO_REFRESH_REQ); + switch_core_media_gen_key_frame(session); } break; case SWITCH_ABC_TYPE_CLOSE: { + switch_core_session_request_video_refresh(session); + switch_channel_set_flag(channel, CF_VIDEO_REFRESH_REQ); + switch_core_media_gen_key_frame(session); + switch_thread_rwlock_unlock(MODULE_INTERFACE->rwlock); switch_img_free(&context->rp_img); @@ -904,6 +921,33 @@ static switch_bool_t video_replace_bug_callback(switch_media_bug_t *bug, void *u } } break; + case SWITCH_ABC_TYPE_WRITE_REPLACE: + case SWITCH_ABC_TYPE_READ_REPLACE: + { + switch_frame_t *rframe = NULL; + switch_size_t len; + + if (type == SWITCH_ABC_TYPE_WRITE_REPLACE) { + rframe = switch_core_media_bug_get_write_replace_frame(bug); + } else { + rframe = switch_core_media_bug_get_read_replace_frame(bug); + } + + if (rframe) { + len = rframe->samples; + + if (switch_test_flag(&context->vfh, SWITCH_FILE_OPEN)) { + switch_core_file_read(&context->vfh, rframe->data, &len); + + if (len < rframe->samples) { + memset((char *)rframe->data + (len * 2 * context->vfh.channels), 0, (rframe->samples - len) * 2 * context->vfh.channels); + } + + rframe->datalen = rframe->samples * 2 * context->vfh.channels; + } + } + } + break; case SWITCH_ABC_TYPE_READ_VIDEO_PING: case SWITCH_ABC_TYPE_WRITE_VIDEO_PING: { @@ -936,7 +980,8 @@ SWITCH_STANDARD_APP(video_replace_start_function) char *argv[2] = { 0 }; char *direction = NULL; char *file = NULL; - + switch_codec_implementation_t read_impl = { 0 }; + if ((bug = (switch_media_bug_t *) switch_channel_get_private(channel, "_video_replace_bug_"))) { if (!zstr(data) && !strcasecmp(data, "stop")) { switch_channel_set_private(channel, "_video_replace_bug_", NULL); @@ -979,7 +1024,9 @@ SWITCH_STANDARD_APP(video_replace_start_function) switch_thread_rwlock_rdlock(MODULE_INTERFACE->rwlock); - if (switch_core_file_open(&context->vfh, file, 1, 8000, + switch_core_session_get_read_impl(session, &read_impl); + + if (switch_core_file_open(&context->vfh, file, read_impl.number_of_channels, read_impl.actual_samples_per_second, SWITCH_FILE_FLAG_READ | SWITCH_FILE_DATA_SHORT | SWITCH_FILE_FLAG_VIDEO, switch_core_session_get_pool(session)) != SWITCH_STATUS_SUCCESS) { switch_log_printf(SWITCH_CHANNEL_LOG, SWITCH_LOG_ERROR, "Error opening video file\n"); @@ -1014,7 +1061,9 @@ SWITCH_STANDARD_API(video_replace_api_function) char *direction = NULL; switch_media_bug_flag_t flags = 0; const char *function = "video_replace"; - + switch_codec_implementation_t read_impl = { 0 }; + int sound = 0; + if (zstr(cmd)) { goto usage; } @@ -1060,10 +1109,18 @@ SWITCH_STANDARD_API(video_replace_api_function) if (zstr(direction) || zstr(file)) goto usage; - if (!strcasecmp(direction, "read")) { + if (!strncasecmp(direction, "read", 4)) { flags = SMBF_READ_VIDEO_PING; - } else if (!strcasecmp(direction, "write")) { + if (switch_stristr(":sound", direction)) { + flags |= SMBF_READ_REPLACE; + sound = 1; + } + } else if (!strncasecmp(direction, "write", 5)) { flags = SMBF_WRITE_VIDEO_PING; + if (switch_stristr(":sound", direction)) { + flags |= SMBF_WRITE_REPLACE; + sound = 1; + } } else { goto usage; } @@ -1079,10 +1136,13 @@ SWITCH_STANDARD_API(video_replace_api_function) context = (video_replace_context_t *) switch_core_session_alloc(rsession, sizeof(*context)); switch_assert(context != NULL); context->session = rsession; - + context->sound = sound; switch_thread_rwlock_rdlock(MODULE_INTERFACE->rwlock); - if (switch_core_file_open(&context->vfh, file, 1, 8000, + + switch_core_session_get_read_impl(rsession, &read_impl); + + if (switch_core_file_open(&context->vfh, file, read_impl.number_of_channels, read_impl.actual_samples_per_second, SWITCH_FILE_FLAG_READ | SWITCH_FILE_DATA_SHORT | SWITCH_FILE_FLAG_VIDEO, switch_core_session_get_pool(rsession)) != SWITCH_STATUS_SUCCESS) { switch_log_printf(SWITCH_CHANNEL_LOG, SWITCH_LOG_ERROR, "Error opening video file\n"); diff --git a/src/mod/applications/mod_vmd/mod_vmd.c b/src/mod/applications/mod_vmd/mod_vmd.c index 71a2dc3bc9..a4a0917404 100644 --- a/src/mod/applications/mod_vmd/mod_vmd.c +++ b/src/mod/applications/mod_vmd/mod_vmd.c @@ -123,7 +123,7 @@ SWITCH_MODULE_SHUTDOWN_FUNCTION(mod_vmd_shutdown); SWITCH_STANDARD_API(vmd_api_main); SWITCH_MODULE_LOAD_FUNCTION(mod_vmd_load); -SWITCH_MODULE_DEFINITION(mod_vmd, mod_vmd_load, NULL, NULL); +SWITCH_MODULE_DEFINITION(mod_vmd, mod_vmd_load, mod_vmd_shutdown, NULL); SWITCH_STANDARD_APP(vmd_start_function); /*! Type that holds state information about the beep. */ diff --git a/src/mod/applications/mod_voicemail/mod_voicemail.c b/src/mod/applications/mod_voicemail/mod_voicemail.c index dd3a74a463..1768f59585 100644 --- a/src/mod/applications/mod_voicemail/mod_voicemail.c +++ b/src/mod/applications/mod_voicemail/mod_voicemail.c @@ -1196,7 +1196,7 @@ static switch_status_t create_file(switch_core_session_t *session, vm_profile_t switch_cc_t cc = { 0 }; switch_codec_implementation_t read_impl = { 0 }; int got_file = 0; - switch_bool_t skip_record_check = switch_true(switch_channel_get_variable(channel, "skip_record_check")); + switch_bool_t skip_record_check = switch_channel_var_true(channel, "skip_record_check"); switch_core_session_get_read_impl(session, &read_impl); @@ -1605,7 +1605,7 @@ static switch_status_t listen_file(switch_core_session_t *session, vm_profile_t cid_buf, switch_channel_get_name(channel)); switch_core_session_receive_message(session, &msg); - if (!zstr(cbt->cid_number) && (switch_true(switch_channel_get_variable(channel, "vm_announce_cid")))) { + if (!zstr(cbt->cid_number) && (switch_channel_var_true(channel, "vm_announce_cid"))) { TRY_CODE(switch_ivr_phrase_macro(session, VM_SAY_PHONE_NUMBER_MACRO, cbt->cid_number, NULL, NULL)); } @@ -2002,7 +2002,7 @@ static void voicemail_check_main(switch_core_session_t *session, vm_profile_t *p auth_only = 1; auth = 0; } else { - auth_only = switch_true(switch_channel_get_variable(channel, "vm_auth_only")); + auth_only = switch_channel_var_true(channel, "vm_auth_only"); } timeout = profile->digit_timeout; @@ -2583,7 +2583,7 @@ static void voicemail_check_main(switch_core_session_t *session, vm_profile_t *p if (!auth) { if (!zstr(cbt.password) && !strcmp(cbt.password, mypass)) { auth++; - } else if (!thepass && profile->allow_empty_password_auth) { + } else if (!thehash && !thepass && profile->allow_empty_password_auth) { auth++; } @@ -3399,14 +3399,16 @@ static switch_status_t voicemail_leave_main(switch_core_session_t *session, vm_p switch_event_t *vars = NULL; const char *vtmp, *vm_ext = NULL; int disk_quota = 0; - switch_bool_t skip_greeting = switch_true(switch_channel_get_variable(channel, "skip_greeting")); - switch_bool_t skip_instructions = switch_true(switch_channel_get_variable(channel, "skip_instructions")); - switch_bool_t skip_record_urgent_check = switch_true(switch_channel_get_variable(channel, "skip_record_urgent_check")); + switch_bool_t skip_greeting = switch_channel_var_true(channel, "skip_greeting"); + switch_bool_t skip_instructions = switch_channel_var_true(channel, "skip_instructions"); + switch_bool_t skip_record_urgent_check = switch_channel_var_true(channel, "skip_record_urgent_check"); + switch_bool_t voicemail_skip_goodbye = switch_channel_var_true(channel, "voicemail_skip_goodbye"); switch_bool_t vm_enabled = SWITCH_TRUE; switch_channel_set_variable(channel, "skip_greeting", NULL); switch_channel_set_variable(channel, "skip_instructions", NULL); switch_channel_set_variable(channel, "skip_record_urgent_check", NULL); + switch_channel_set_variable(channel, "voicemail_skip_goodbye", NULL); memset(&cbt, 0, sizeof(cbt)); @@ -3700,7 +3702,9 @@ static switch_status_t voicemail_leave_main(switch_core_session_t *session, vm_p switch_safe_free(file_path); if (switch_channel_ready(channel) && vm_enabled) { - status = switch_ivr_phrase_macro(session, VM_GOODBYE_MACRO, NULL, NULL, NULL); + if (!voicemail_skip_goodbye) { + status = switch_ivr_phrase_macro(session, VM_GOODBYE_MACRO, NULL, NULL, NULL); + } } return status; diff --git a/src/mod/applications/mod_voicemail_ivr/menu.c b/src/mod/applications/mod_voicemail_ivr/menu.c index 79aa16b56e..8a21353c93 100644 --- a/src/mod/applications/mod_voicemail_ivr/menu.c +++ b/src/mod/applications/mod_voicemail_ivr/menu.c @@ -730,13 +730,15 @@ char *vmivr_menu_get_input_set(switch_core_session_t *session, vmivr_profile_t * for (retry = menu->ivr_maximum_attempts; switch_channel_ready(channel) && retry > 0; retry--) { int i; + int dtmfa_array_length = 0; menu_instance_init(menu); switch_event_add_header(menu->phrase_params, SWITCH_STACK_BOTTOM, "IVR-Retry-Left", "%d", retry); /* Find the last entry and append this one to it */ - for (i=0; i < 16 && menu->dtmfa[i]; i++){ + dtmfa_array_length = sizeof(menu->dtmfa) / sizeof(menu->dtmfa[0]); + for (i = 0; i < (dtmfa_array_length - 1) && menu->dtmfa[i]; i++){ } menu->dtmfa[i] = (char *) input_mask; diff --git a/src/mod/codecs/mod_openh264/mod_openh264.cpp b/src/mod/codecs/mod_openh264/mod_openh264.cpp index 8770a71818..be92f63b7f 100644 --- a/src/mod/codecs/mod_openh264/mod_openh264.cpp +++ b/src/mod/codecs/mod_openh264/mod_openh264.cpp @@ -77,6 +77,7 @@ typedef struct h264_codec_context_s { switch_bool_t last_received_complete_picture; switch_codec_settings_t codec_settings; unsigned int bandwidth; + int32_t debug; } h264_codec_context_t; int FillSpecificParameters(h264_codec_context_t *context) { @@ -745,6 +746,12 @@ static switch_status_t switch_h264_control(switch_codec_t *codec, h264_codec_context_t *context = (h264_codec_context_t *)codec->private_info; switch(cmd) { + case SCC_DEBUG: + { + int32_t level = *((uint32_t *) cmd_data); + context->debug = level; + } + break; case SCC_VIDEO_GEN_KEYFRAME: context->need_key_frame = 1; break; diff --git a/src/mod/databases/mod_pgsql/mod_pgsql.c b/src/mod/databases/mod_pgsql/mod_pgsql.c index 8c24cf9fce..b638a4feae 100644 --- a/src/mod/databases/mod_pgsql/mod_pgsql.c +++ b/src/mod/databases/mod_pgsql/mod_pgsql.c @@ -774,6 +774,11 @@ switch_status_t pgsql_next_result_timed(switch_pgsql_handle_t *handle, switch_pg case PGRES_COPY_IN: case PGRES_COMMAND_OK: break; +#if POSTGRESQL_MAJOR_VERSION >= 14 + case PGRES_PIPELINE_ABORTED: + case PGRES_PIPELINE_SYNC: + break; +#endif case PGRES_EMPTY_QUERY: switch_log_printf(SWITCH_CHANNEL_LOG, SWITCH_LOG_DEBUG, "Query (%s) returned PGRES_EMPTY_QUERY\n", handle->sql); case PGRES_BAD_RESPONSE: diff --git a/src/mod/dialplans/mod_dialplan_xml/mod_dialplan_xml.c b/src/mod/dialplans/mod_dialplan_xml/mod_dialplan_xml.c index 005276dcd3..f85a9855bb 100644 --- a/src/mod/dialplans/mod_dialplan_xml/mod_dialplan_xml.c +++ b/src/mod/dialplans/mod_dialplan_xml/mod_dialplan_xml.c @@ -361,6 +361,7 @@ static int parse_exten(switch_core_session_t *session, switch_caller_profile_t * switch_regex_safe_free(re); switch_safe_free(field_expanded); + if (expression == expression_expanded) expression = NULL; switch_safe_free(expression_expanded); } @@ -375,6 +376,7 @@ static int parse_exten(switch_core_session_t *session, switch_caller_profile_t * } switch_safe_free(field_expanded); + if (expression == expression_expanded) expression = NULL; switch_safe_free(expression_expanded); } else { if ((xexpression = switch_xml_child(xcond, "expression"))) { @@ -502,7 +504,7 @@ static int parse_exten(switch_core_session_t *session, switch_caller_profile_t * proceed = 1; } } else { - if (field && strchr(expression, '(')) { + if (field && expression && strchr(expression, '(')) { switch_channel_set_variable(channel, "DP_MATCH", NULL); switch_capture_regex(re, proceed, field_data, ovector, "DP_MATCH", switch_regex_set_var_callback, session); } @@ -524,7 +526,7 @@ static int parse_exten(switch_core_session_t *session, switch_caller_profile_t * data = (char *) switch_xml_attr_soft(xaction, "data"); } - if (field && strchr(expression, '(')) { + if (field && expression && strchr(expression, '(')) { len = (uint32_t) (strlen(data) + strlen(field_data) + 10) * proceed; if (!(substituted = malloc(len))) { switch_log_printf(SWITCH_CHANNEL_SESSION_LOG(session), SWITCH_LOG_CRIT, "Memory Error!\n"); diff --git a/src/mod/endpoints/mod_loopback/mod_loopback.c b/src/mod/endpoints/mod_loopback/mod_loopback.c index 6fa0d4fbd4..456936562a 100644 --- a/src/mod/endpoints/mod_loopback/mod_loopback.c +++ b/src/mod/endpoints/mod_loopback/mod_loopback.c @@ -25,6 +25,7 @@ * * Anthony Minessale II * Emmanuel Schmidbauer + * Seven Du * * * mod_loopback.c -- Loopback Endpoint Module @@ -1302,6 +1303,9 @@ struct null_private_object { switch_codec_t read_codec; switch_codec_t write_codec; switch_timer_t timer; + switch_codec_t video_read_codec; + switch_codec_t video_write_codec; + switch_timer_t video_timer; switch_caller_profile_t *caller_profile; switch_frame_t read_frame; int16_t *null_buf; @@ -1312,6 +1316,12 @@ struct null_private_object { int enable_auto_answer; /* auto_answer_delay (0 ms by default) */ int auto_answer_delay; + char *video_codec_name; + switch_frame_t video_read_frame; + uint8_t video_data[SWITCH_RECOMMENDED_BUFFER_SIZE]; + switch_image_t *img; + switch_media_handle_t *media_handle; + switch_core_media_params_t mparams; }; typedef struct null_private_object null_private_t; @@ -1324,9 +1334,31 @@ static switch_call_cause_t null_channel_outgoing_channel(switch_core_session_t * switch_call_cause_t *cancel_cause); static switch_status_t null_channel_read_frame(switch_core_session_t *session, switch_frame_t **frame, switch_io_flag_t flags, int stream_id); static switch_status_t null_channel_write_frame(switch_core_session_t *session, switch_frame_t *frame, switch_io_flag_t flags, int stream_id); +static switch_status_t null_channel_read_video_frame(switch_core_session_t *session, switch_frame_t **frame, switch_io_flag_t flags, int stream_id); +static switch_status_t null_channel_write_video_frame(switch_core_session_t *session, switch_frame_t *frame, switch_io_flag_t flags, int stream_id); static switch_status_t null_channel_kill_channel(switch_core_session_t *session, int sig); +static void set_mparams(null_private_t *tech_pvt) +{ + switch_core_media_params_t *mparams = &tech_pvt->mparams; + mparams->inbound_codec_string = "L16"; + mparams->outbound_codec_string = "L16"; + mparams->timer_name = "soft"; + mparams->extsipip = "10.0.0.1"; + mparams->extrtpip = "10.0.0.2"; + mparams->local_network = "127.0.0.1"; + mparams->sipip = "127.0.0.1"; + mparams->rtpip = "127.0.0.1"; + mparams->jb_msec = "60"; + mparams->rtcp_audio_interval_msec = "5000"; + mparams->rtcp_video_interval_msec = "5000"; + mparams->sdp_username = "FreeSWITCH"; + mparams->cng_pt = 13; + mparams->rtp_timeout_sec = 300; + mparams->rtp_hold_timeout_sec = 3600; + mparams->external_video_source = 1; +} static switch_status_t null_tech_init(null_private_t *tech_pvt, switch_core_session_t *session) { @@ -1364,6 +1396,43 @@ static switch_status_t null_tech_init(null_private_t *tech_pvt, switch_core_sess switch_core_session_set_read_codec(session, &tech_pvt->read_codec); switch_core_session_set_write_codec(session, &tech_pvt->write_codec); + if (!zstr(tech_pvt->video_codec_name)) { + status = switch_core_codec_init(&tech_pvt->video_read_codec, + tech_pvt->video_codec_name, + NULL, + NULL, + 90000, 0, 0, SWITCH_CODEC_FLAG_ENCODE | SWITCH_CODEC_FLAG_DECODE, NULL, switch_core_session_get_pool(session)); + + if (status != SWITCH_STATUS_SUCCESS || !tech_pvt->video_read_codec.implementation || !switch_core_codec_ready(&tech_pvt->video_read_codec)) { + goto end; + } + + status = switch_core_codec_init(&tech_pvt->video_write_codec, + tech_pvt->video_codec_name, + NULL, + NULL, + 90000, 0, 0, SWITCH_CODEC_FLAG_ENCODE | SWITCH_CODEC_FLAG_DECODE, NULL, switch_core_session_get_pool(session)); + + + if (status != SWITCH_STATUS_SUCCESS) { + switch_core_codec_destroy(&tech_pvt->video_read_codec); + goto end; + } + + switch_channel_set_flag(switch_core_session_get_channel(session), CF_VIDEO); + switch_core_session_set_video_read_codec(session, &tech_pvt->read_codec); + switch_core_session_set_video_write_codec(session, &tech_pvt->write_codec); + switch_core_timer_init(&tech_pvt->video_timer, "soft", 100, 900, switch_core_session_get_pool(session)); + set_mparams(tech_pvt); + switch_media_handle_create(&tech_pvt->media_handle, session, &tech_pvt->mparams); + // switch_core_media_prepare_codecs(session, SWITCH_TRUE); + // switch_core_media_check_video_codecs(session); + // switch_core_media_choose_port(session, SWITCH_MEDIA_TYPE_AUDIO, 0); + // switch_core_media_choose_port(session, SWITCH_MEDIA_TYPE_VIDEO, 0); + // switch_core_media_gen_local_sdp(session, SDP_TYPE_REQUEST, "127.0.0.1", 2000, NULL, 0); + // switch_log_printf(SWITCH_CHANNEL_LOG, SWITCH_LOG_INFO, "%s\n", mparams.local_sdp_str); + } + read_impl = tech_pvt->read_codec.implementation; switch_core_timer_init(&tech_pvt->timer, "soft", @@ -1419,8 +1488,20 @@ static switch_status_t null_channel_on_destroy(switch_core_session_t *session) if (switch_core_codec_ready(&tech_pvt->write_codec)) { switch_core_codec_destroy(&tech_pvt->write_codec); } + + if (switch_core_codec_ready(&tech_pvt->video_read_codec)) { + switch_core_codec_destroy(&tech_pvt->video_read_codec); + } + + if (switch_core_codec_ready(&tech_pvt->video_write_codec)) { + switch_core_codec_destroy(&tech_pvt->video_write_codec); + } + + switch_img_free(&tech_pvt->img); } + switch_media_handle_destroy(session); + return SWITCH_STATUS_SUCCESS; } @@ -1558,6 +1639,50 @@ static switch_status_t null_channel_write_frame(switch_core_session_t *session, return SWITCH_STATUS_SUCCESS; } +static switch_status_t null_channel_read_video_frame(switch_core_session_t *session, switch_frame_t **frame, switch_io_flag_t flags, int stream_id) +{ + switch_channel_t *channel = NULL; + null_private_t *tech_pvt = NULL; + switch_status_t status = SWITCH_STATUS_FALSE; + + channel = switch_core_session_get_channel(session); + switch_assert(channel != NULL); + + tech_pvt = switch_core_session_get_private(session); + switch_assert(tech_pvt != NULL); + + *frame = NULL; + + if (!switch_channel_ready(channel)) { + return SWITCH_STATUS_FALSE; + } + + switch_core_timer_next(&tech_pvt->video_timer); + + tech_pvt->video_read_frame.codec = &tech_pvt->video_read_codec; + tech_pvt->video_read_frame.datalen = 0; + tech_pvt->video_read_frame.buflen = SWITCH_RECOMMENDED_BUFFER_SIZE; + tech_pvt->video_read_frame.samples = 0; + tech_pvt->video_read_frame.data = tech_pvt->video_data; + if (!tech_pvt->img) { + tech_pvt->img = switch_img_alloc(NULL, SWITCH_IMG_FMT_I420, 1280, 720, 0); + } + tech_pvt->video_read_frame.img = tech_pvt->img; + *frame = &tech_pvt->video_read_frame; + + if (*frame) { + status = SWITCH_STATUS_SUCCESS; + } else { + status = SWITCH_STATUS_FALSE; + } + + return status; +} +static switch_status_t null_channel_write_video_frame(switch_core_session_t *session, switch_frame_t *frame, switch_io_flag_t flags, int stream_id) +{ + return SWITCH_STATUS_SUCCESS; +} + static switch_status_t null_channel_receive_message(switch_core_session_t *session, switch_core_session_message_t *msg) { switch_channel_t *channel; @@ -1638,6 +1763,7 @@ static switch_call_cause_t null_channel_outgoing_channel(switch_core_session_t * if ((tech_pvt = (null_private_t *) switch_core_session_alloc(*new_session, sizeof(null_private_t))) != 0) { const char *rate_ = switch_event_get_header(var_event, "rate"); + const char *video_codec = switch_event_get_header(var_event, "null_video_codec"); int rate = 0; if (rate_) { @@ -1649,9 +1775,12 @@ static switch_call_cause_t null_channel_outgoing_channel(switch_core_session_t * } tech_pvt->rate = rate; - tech_pvt->pre_answer = switch_true(pre_answer); + if (video_codec) { + tech_pvt->video_codec_name = switch_core_session_strdup(*new_session, video_codec); + } + if (!enable_auto_answer) { /* if not set - enabled by default */ tech_pvt->enable_auto_answer = SWITCH_TRUE; @@ -1733,7 +1862,15 @@ static switch_io_routines_t null_channel_io_routines = { /*.write_frame */ null_channel_write_frame, /*.kill_channel */ null_channel_kill_channel, /*.send_dtmf */ null_channel_send_dtmf, - /*.receive_message */ null_channel_receive_message + /*.receive_message */ null_channel_receive_message, + /*.receive_event */ NULL, + /*.state_change */ NULL, + /*.read_video_frame */ null_channel_read_video_frame, + /*.write_video_frame */ null_channel_write_video_frame, + /*.read_text_frame */ NULL, + /*.write_text_frame */ NULL, + /*.state_run*/ NULL, + /*.get_jb*/ NULL }; switch_status_t load_loopback_configuration(switch_bool_t reload) diff --git a/src/mod/endpoints/mod_skinny/mod_skinny.c b/src/mod/endpoints/mod_skinny/mod_skinny.c index 0274912ad2..3df1290047 100644 --- a/src/mod/endpoints/mod_skinny/mod_skinny.c +++ b/src/mod/endpoints/mod_skinny/mod_skinny.c @@ -2414,7 +2414,7 @@ static switch_status_t load_skinny_config(void) char *val = (char *) switch_xml_attr_soft(param, "value"); if (!strcasecmp(var, "firmware-version")) { - strncpy(params->firmware_version, val, 16); + snprintf(params->firmware_version, 16, "%s", val); } } /* param */ switch_core_hash_insert(profile->device_type_params_hash, id_str, params); diff --git a/src/mod/endpoints/mod_sofia/conf/sofia.conf.xml b/src/mod/endpoints/mod_sofia/conf/sofia.conf.xml index 3166094a27..0f5db4468f 100644 --- a/src/mod/endpoints/mod_sofia/conf/sofia.conf.xml +++ b/src/mod/endpoints/mod_sofia/conf/sofia.conf.xml @@ -205,6 +205,8 @@ + + @@ -330,6 +332,14 @@ disable-auth-messages param has higher priority than the deprecated auth-messages param. --> + + + + + + + + + + ;tag=[call_number] + To: sut + Call-ID: [call_id] + CSeq: 1 INVITE + Contact: sip:s_sipp@[local_ip]:[local_port] + Max-Forwards: 70 + Subject: Performance Test + Content-Type: application/sdp + Content-Length: [len] + + v=0 + o=CiscoSystemsCCM-SIP 1195507 1 IN IP[local_ip_type] [local_ip] + s=SIP Call + c=IN IP[local_ip_type] [local_ip] + b=TIAS:64000 + b=AS:80 + t=0 0 + m=audio [auto_media_port] RTP/SAVP 18 0 8 100 + a=rtpmap:0 PCMU/8000 + a=rtpmap:8 PCMA/8000 + a=rtpmap:18 G729/8000 + a=fmtp:18 annexb=no + a=rtpmap:100 telephone-event/8000 + a=fmtp:100 0-15 + a=crypto:1 AES_CM_128_HMAC_SHA1_80 inline:mSPPjYxzAEWkICVXidkYXFdsHr/J2NhpkqQepffH + + ]]> + + + + + + + + + + + + + + + + + + + + + ;tag=[call_number] + To: sut [peer_tag_param] + Call-ID: [call_id] + CSeq: 1 ACK + Contact: sip:s_sipp@[local_ip]:[local_port] + Max-Forwards: 70 + Subject: Performance Test + Content-Length: 0 + + ]]> + + + + + + ;tag=[call_number] + To: sut + Call-ID: [call_id] + CSeq: 2 INVITE + Contact: sip:s_sipp@[local_ip]:[local_port] + Max-Forwards: 70 + Subject: Performance Test + Content-Length: [len] + + ]]> + + + + + + + + + + ;tag=[call_number] + To: sut [peer_tag_param] + Call-ID: [call_id] + CSeq: 2 ACK + Contact: sip:s_sipp@[local_ip]:[local_port] + Max-Forwards: 70 + Subject: Performance Test + Content-Type: application/sdp + Content-Length: [len] + + + ]]> + + + + + ;tag=[call_number] + To: sut [peer_tag_param] + Call-ID: [call_id] + CSeq: 3 BYE + Contact: sip:s_sipp@[local_ip]:[local_port] + Max-Forwards: 70 + Subject: Performance Test + Content-Length: 0 + + ]]> + + + + + + + + + + + + + + diff --git a/src/mod/endpoints/mod_sofia/test/sipp-scenarios/uac_subscriber.xml b/src/mod/endpoints/mod_sofia/test/sipp-scenarios/uac_subscriber.xml new file mode 100644 index 0000000000..69107bd39d --- /dev/null +++ b/src/mod/endpoints/mod_sofia/test/sipp-scenarios/uac_subscriber.xml @@ -0,0 +1,28 @@ + + + + + ;tag=[pid]SIPpTag00[call_number] + To: sut + Call-ID: [call_id] + CSeq: 1 SUBSCRIBE + Contact: sip:[service]@[local_ip]:[local_port] + Max-Forwards: 70 + Event: presence + Allow: SUBSCRIBE + Expires: 120 + Accept: application/simple-message-summary + Allow-Events: presence, kpml + Content-Length: 0 + + ]]> + + + + + + diff --git a/src/mod/endpoints/mod_sofia/test/sipp-scenarios/uac_telephone_event.xml b/src/mod/endpoints/mod_sofia/test/sipp-scenarios/uac_telephone_event.xml new file mode 100644 index 0000000000..c3e905de93 --- /dev/null +++ b/src/mod/endpoints/mod_sofia/test/sipp-scenarios/uac_telephone_event.xml @@ -0,0 +1,159 @@ + + + + + + ;tag=[call_number] + To: sut + Call-ID: [call_id] + CSeq: 1 INVITE + Contact: sip:t_sipp@[local_ip]:[local_port] + Max-Forwards: 70 + Subject: Performance Test + Content-Type: application/sdp + Content-Length: [len] + + v=0 + o=user1 53655765 2353687637 IN IP[local_ip_type] [local_ip] + s=- + c=IN IP[local_ip_type] [local_ip] + t=0 0 + m=audio [auto_media_port] RTP/AVP 8 0 18 101 + a=rtpmap:8 PCMA/8000 + a=rtpmap:0 PCMU/8000 + a=rtpmap:18 G729/8000 + a=fmtp:18 annexb=no + a=rtpmap:101 telephone-event/8000 + a=fmtp:101 0-11,16 + a=sendrecv + a=ptime:20 + ]]> + + + + + + + + + + + + + + + + + + ;tag=[call_number] + To: sut [peer_tag_param] + Call-ID: [call_id] + CSeq: 1 ACK + Contact: sip:t_sipp@[local_ip]:[local_port] + Max-Forwards: 70 + Subject: Performance Test + Content-Length: 0 + + ]]> + + + + + + ;tag=[call_number] + To: sut + Call-ID: [call_id] + CSeq: 2 INVITE + Contact: sip:t_sipp@[local_ip]:[local_port] + Max-Forwards: 70 + Subject: Performance Test + Content-Length: [len] + + ]]> + + + + + + + + + + + ;tag=[call_number] + To: sut [peer_tag_param] + Call-ID: [call_id] + CSeq: 2 ACK + Contact: sip:t_sipp@[local_ip]:[local_port] + Max-Forwards: 70 + Subject: Performance Test + Content-Type: application/sdp + Content-Length: [len] + + v=0 + o=user1 53655765 2353687637 IN IP[local_ip_type] [local_ip] + s= + c=IN IP[local_ip_type] [local_ip] + t=0 0 + m=audio [auto_media_port] RTP/AVP 8 0 101 + a=rtpmap:8 PCMA/8000 + a=rtpmap:0 PCMU/8000 + a=rtpmap:101 telephone-event/8000 + a=fmtp:101 0-15 + a=sendrecv + a=ptime:20 + + ]]> + + + + ;tag=[call_number] + To: sut [peer_tag_param] + Call-ID: [call_id] + CSeq: 3 BYE + Contact: sip:t_sipp@[local_ip]:[local_port] + Max-Forwards: 70 + Subject: Performance Test + Content-Length: 0 + + ]]> + + + + + + + + + + + + + + diff --git a/src/mod/endpoints/mod_sofia/test/test_sofia_funcs.c b/src/mod/endpoints/mod_sofia/test/test_sofia_funcs.c index e769057363..7ea194f6e4 100644 --- a/src/mod/endpoints/mod_sofia/test/test_sofia_funcs.c +++ b/src/mod/endpoints/mod_sofia/test/test_sofia_funcs.c @@ -33,6 +33,8 @@ #include #include "../mod_sofia.c" +static int timeout_sec = 10; + FST_CORE_EX_BEGIN("./conf", SCF_VG | SCF_USE_SQL) FST_MODULE_BEGIN(mod_sofia, sofia) @@ -101,17 +103,20 @@ FST_TEST_BEGIN(originate_test) switch_status_t status; switch_call_cause_t cause; const char *local_ip_v4 = switch_core_get_variable("local_ip_v4"); - status = switch_ivr_originate(NULL, &session, &cause, switch_core_sprintf(fst_pool, "{ignore_early_media=true}sofia/internal/park@%s:53060", local_ip_v4), 2, NULL, NULL, NULL, NULL, NULL, SOF_NONE, NULL, NULL); - fst_requires(session); + status = switch_ivr_originate(NULL, &session, &cause, switch_core_sprintf(fst_pool, "{ignore_early_media=true}sofia/internal/park@%s:53060", local_ip_v4), timeout_sec, NULL, NULL, NULL, NULL, NULL, SOF_NONE, NULL, NULL); + fst_check(session); fst_check(status == SWITCH_STATUS_SUCCESS); - channel = switch_core_session_get_channel(session); - fst_requires(channel); - switch_channel_hangup(channel, SWITCH_CAUSE_NORMAL_CLEARING); - switch_core_session_rwunlock(session); - switch_sleep(1 * 1000 * 1000); + if (session) { + channel = switch_core_session_get_channel(session); + fst_requires(channel); + switch_channel_hangup(channel, SWITCH_CAUSE_NORMAL_CLEARING); + switch_core_session_rwunlock(session); + switch_sleep(1 * 1000 * 1000); + } } FST_TEST_END() +#if HAVE_STIRSHAKEN FST_TEST_BEGIN(sofia_verify_identity_test_no_identity) { switch_core_session_t *session = NULL; @@ -119,7 +124,7 @@ FST_TEST_BEGIN(sofia_verify_identity_test_no_identity) switch_status_t status; switch_call_cause_t cause; const char *local_ip_v4 = switch_core_get_variable("local_ip_v4"); - status = switch_ivr_originate(NULL, &session, &cause, switch_core_sprintf(fst_pool, "{ignore_early_media=true}sofia/internal/verifyidentity@%s:53060", local_ip_v4), 2, NULL, NULL, NULL, NULL, NULL, SOF_NONE, NULL, NULL); + status = switch_ivr_originate(NULL, &session, &cause, switch_core_sprintf(fst_pool, "{ignore_early_media=true}sofia/internal/verifyidentity@%s:53060", local_ip_v4), timeout_sec, NULL, NULL, NULL, NULL, NULL, SOF_NONE, NULL, NULL); fst_check(status != SWITCH_STATUS_SUCCESS); fst_check(cause == SWITCH_CAUSE_NO_IDENTITY); if (session) { @@ -138,7 +143,7 @@ FST_TEST_BEGIN(sofia_verify_identity_test_bad_identity) switch_status_t status; switch_call_cause_t cause; const char *local_ip_v4 = switch_core_get_variable("local_ip_v4"); - status = switch_ivr_originate(NULL, &session, &cause, switch_core_sprintf(fst_pool, "{ignore_early_media=true,sip_h_identity=foo;info=bar}sofia/internal/verifyidentity@%s:53060", local_ip_v4), 2, NULL, NULL, NULL, NULL, NULL, SOF_NONE, NULL, NULL); + status = switch_ivr_originate(NULL, &session, &cause, switch_core_sprintf(fst_pool, "{ignore_early_media=true,sip_h_identity=foo;info=bar}sofia/internal/verifyidentity@%s:53060", local_ip_v4), timeout_sec, NULL, NULL, NULL, NULL, NULL, SOF_NONE, NULL, NULL); fst_check(status != SWITCH_STATUS_SUCCESS); fst_check(cause == SWITCH_CAUSE_INVALID_IDENTITY); if (session) { @@ -157,7 +162,7 @@ FST_TEST_BEGIN(sofia_verify_identity_test_valid_identity_no_cert_available) switch_status_t status; switch_call_cause_t cause; const char *local_ip_v4 = switch_core_get_variable("local_ip_v4"); - status = switch_ivr_originate(NULL, &session, &cause, switch_core_sprintf(fst_pool, "{origination_caller_id_number=+15551231234,ignore_early_media=true,sip_h_identity=eyJhbGciOiJFUzI1NiIsInBwdCI6InNoYWtlbiIsInR5cCI6InBhc3Nwb3J0IiwieDV1IjoiaHR0cDovLzEyNy4wLjAuMS80MDQucGVtIn0.eyJhdHRlc3QiOiJBIiwiZGVzdCI6eyJ0biI6WyIxNTU1MzIxNDMyMSJdfSwiaWF0IjoxNjE4Mjc5OTYzLCJvcmlnIjp7InRuIjoiMTU1NTEyMzEyMzQifSwib3JpZ2lkIjoiMTMxMzEzMTMifQ.Cm34sISkFWYB6ohtjjJEO71Hyz4TQ5qrTDyYmCXBj-ni5Fe7IbNjmMyvY_lD_Go0u2csWQNe8n03fHSO7Z7nNw;info=;alg=ES256;ppt=shaken}sofia/internal/+15553214321@%s:53060", local_ip_v4), 2, NULL, NULL, NULL, NULL, NULL, SOF_NONE, NULL, NULL); + status = switch_ivr_originate(NULL, &session, &cause, switch_core_sprintf(fst_pool, "{origination_caller_id_number=+15551231234,ignore_early_media=true,sip_h_identity=eyJhbGciOiJFUzI1NiIsInBwdCI6InNoYWtlbiIsInR5cCI6InBhc3Nwb3J0IiwieDV1IjoiaHR0cDovLzEyNy4wLjAuMS80MDQucGVtIn0.eyJhdHRlc3QiOiJBIiwiZGVzdCI6eyJ0biI6WyIxNTU1MzIxNDMyMSJdfSwiaWF0IjoxNjE4Mjc5OTYzLCJvcmlnIjp7InRuIjoiMTU1NTEyMzEyMzQifSwib3JpZ2lkIjoiMTMxMzEzMTMifQ.Cm34sISkFWYB6ohtjjJEO71Hyz4TQ5qrTDyYmCXBj-ni5Fe7IbNjmMyvY_lD_Go0u2csWQNe8n03fHSO7Z7nNw;info=;alg=ES256;ppt=shaken}sofia/internal/+15553214321@%s:53060", local_ip_v4), timeout_sec, NULL, NULL, NULL, NULL, NULL, SOF_NONE, NULL, NULL); fst_check(status != SWITCH_STATUS_SUCCESS); fst_check(cause == SWITCH_CAUSE_INVALID_IDENTITY); if (session) { @@ -176,13 +181,15 @@ FST_TEST_BEGIN(sofia_auth_identity_test_attest_a) switch_status_t status; switch_call_cause_t cause; const char *local_ip_v4 = switch_core_get_variable("local_ip_v4"); - status = switch_ivr_originate(NULL, &session, &cause, switch_core_sprintf(fst_pool, "{origination_caller_id_number=+15551231234,ignore_early_media=true,sip_stir_shaken_attest=A}sofia/internal/+15553214322@%s:53060", local_ip_v4), 2, NULL, NULL, NULL, NULL, NULL, SOF_NONE, NULL, NULL); + status = switch_ivr_originate(NULL, &session, &cause, switch_core_sprintf(fst_pool, "{origination_caller_id_number=+15551231234,ignore_early_media=true,sip_stir_shaken_attest=A}sofia/internal/+15553214322@%s:53060", local_ip_v4), timeout_sec, NULL, NULL, NULL, NULL, NULL, SOF_NONE, NULL, NULL); fst_check(status == SWITCH_STATUS_SUCCESS); - fst_requires(session); - channel = switch_core_session_get_channel(session); - switch_channel_hangup(channel, SWITCH_CAUSE_NORMAL_CLEARING); - switch_core_session_rwunlock(session); - switch_sleep(1 * 1000 * 1000); + fst_check(session); + if (session) { + channel = switch_core_session_get_channel(session); + switch_channel_hangup(channel, SWITCH_CAUSE_NORMAL_CLEARING); + switch_core_session_rwunlock(session); + switch_sleep(1 * 1000 * 1000); + } } FST_TEST_END() @@ -193,13 +200,15 @@ FST_TEST_BEGIN(sofia_auth_identity_test_attest_b) switch_status_t status; switch_call_cause_t cause; const char *local_ip_v4 = switch_core_get_variable("local_ip_v4"); - status = switch_ivr_originate(NULL, &session, &cause, switch_core_sprintf(fst_pool, "{origination_caller_id_number=+15551231234,ignore_early_media=true,sip_stir_shaken_attest=B}sofia/internal/+15553214322@%s:53060", local_ip_v4), 2, NULL, NULL, NULL, NULL, NULL, SOF_NONE, NULL, NULL); + status = switch_ivr_originate(NULL, &session, &cause, switch_core_sprintf(fst_pool, "{origination_caller_id_number=+15551231234,ignore_early_media=true,sip_stir_shaken_attest=B}sofia/internal/+15553214322@%s:53060", local_ip_v4), timeout_sec, NULL, NULL, NULL, NULL, NULL, SOF_NONE, NULL, NULL); fst_check(status == SWITCH_STATUS_SUCCESS); - fst_requires(session); - channel = switch_core_session_get_channel(session); - switch_channel_hangup(channel, SWITCH_CAUSE_NORMAL_CLEARING); - switch_core_session_rwunlock(session); - switch_sleep(1 * 1000 * 1000); + fst_check(session); + if (session) { + channel = switch_core_session_get_channel(session); + switch_channel_hangup(channel, SWITCH_CAUSE_NORMAL_CLEARING); + switch_core_session_rwunlock(session); + switch_sleep(1 * 1000 * 1000); + } } FST_TEST_END() @@ -210,13 +219,15 @@ FST_TEST_BEGIN(sofia_auth_identity_test_attest_c) switch_status_t status; switch_call_cause_t cause; const char *local_ip_v4 = switch_core_get_variable("local_ip_v4"); - status = switch_ivr_originate(NULL, &session, &cause, switch_core_sprintf(fst_pool, "{origination_caller_id_number=+15551231234,ignore_early_media=true,sip_stir_shaken_attest=C}sofia/internal/+15553214322@%s:53060", local_ip_v4), 2, NULL, NULL, NULL, NULL, NULL, SOF_NONE, NULL, NULL); + status = switch_ivr_originate(NULL, &session, &cause, switch_core_sprintf(fst_pool, "{origination_caller_id_number=+15551231234,ignore_early_media=true,sip_stir_shaken_attest=C}sofia/internal/+15553214322@%s:53060", local_ip_v4), timeout_sec, NULL, NULL, NULL, NULL, NULL, SOF_NONE, NULL, NULL); fst_check(status == SWITCH_STATUS_SUCCESS); - fst_requires(session); - channel = switch_core_session_get_channel(session); - switch_channel_hangup(channel, SWITCH_CAUSE_NORMAL_CLEARING); - switch_core_session_rwunlock(session); - switch_sleep(1 * 1000 * 1000); + fst_check(session); + if (session) { + channel = switch_core_session_get_channel(session); + switch_channel_hangup(channel, SWITCH_CAUSE_NORMAL_CLEARING); + switch_core_session_rwunlock(session); + switch_sleep(1 * 1000 * 1000); + } } FST_TEST_END() @@ -227,7 +238,7 @@ FST_TEST_BEGIN(sofia_verify_identity_test_verified_attest_a_expired) switch_status_t status; switch_call_cause_t cause; const char *local_ip_v4 = switch_core_get_variable("local_ip_v4"); - status = switch_ivr_originate(NULL, &session, &cause, switch_core_sprintf(fst_pool, "{origination_caller_id_number=+15551231234,ignore_early_media=true,sip_h_identity=eyJhbGciOiJFUzI1NiIsInBwdCI6InNoYWtlbiIsInR5cCI6InBhc3Nwb3J0IiwieDV1IjoiaHR0cDovLzEyNy4wLjAuMTo4MDgwL2NlcnQucGVtIn0.eyJhdHRlc3QiOiJBIiwiZGVzdCI6eyJ0biI6WyIxNTU1MzIxNDMyMiJdfSwiaWF0IjoxNjE4MzczMTc0LCJvcmlnIjp7InRuIjoiMTU1NTEyMzEyMzQifSwib3JpZ2lkIjoiMzliZDYzZDQtOTE1Mi00MzU0LWFkNjctNjg5NjQ2NmI4ZDI3In0.mUaikwHSOb8RVPwwMZTsqBe57MZY29CgbIqmiiEmyq9DzKZO-y4qShiIVT3serg-xHgC9SCMjUOBWaDfeXnEvA;info=;alg=ES256;ppt=shaken}sofia/internal/+15553214322@%s:53060", local_ip_v4), 2, NULL, NULL, NULL, NULL, NULL, SOF_NONE, NULL, NULL); + status = switch_ivr_originate(NULL, &session, &cause, switch_core_sprintf(fst_pool, "{origination_caller_id_number=+15551231234,ignore_early_media=true,sip_h_identity=eyJhbGciOiJFUzI1NiIsInBwdCI6InNoYWtlbiIsInR5cCI6InBhc3Nwb3J0IiwieDV1IjoiaHR0cDovLzEyNy4wLjAuMTo4MDgwL2NlcnQucGVtIn0.eyJhdHRlc3QiOiJBIiwiZGVzdCI6eyJ0biI6WyIxNTU1MzIxNDMyMiJdfSwiaWF0IjoxNjE4MzczMTc0LCJvcmlnIjp7InRuIjoiMTU1NTEyMzEyMzQifSwib3JpZ2lkIjoiMzliZDYzZDQtOTE1Mi00MzU0LWFkNjctNjg5NjQ2NmI4ZDI3In0.mUaikwHSOb8RVPwwMZTsqBe57MZY29CgbIqmiiEmyq9DzKZO-y4qShiIVT3serg-xHgC9SCMjUOBWaDfeXnEvA;info=;alg=ES256;ppt=shaken}sofia/internal/+15553214322@%s:53060", local_ip_v4), timeout_sec, NULL, NULL, NULL, NULL, NULL, SOF_NONE, NULL, NULL); fst_check(status != SWITCH_STATUS_SUCCESS); fst_check(cause == SWITCH_CAUSE_CALL_REJECTED); if (session) { @@ -246,15 +257,18 @@ FST_TEST_BEGIN(sofia_auth_identity_test_attest_a_date) switch_status_t status; switch_call_cause_t cause; const char *local_ip_v4 = switch_core_get_variable("local_ip_v4"); - status = switch_ivr_originate(NULL, &session, &cause, switch_core_sprintf(fst_pool, "{origination_caller_id_number=+15551231235,ignore_early_media=true,sip_stir_shaken_attest=A}sofia/internal/+15553214323@%s:53060", local_ip_v4), 2, NULL, NULL, NULL, NULL, NULL, SOF_NONE, NULL, NULL); + status = switch_ivr_originate(NULL, &session, &cause, switch_core_sprintf(fst_pool, "{origination_caller_id_number=+15551231235,ignore_early_media=true,sip_stir_shaken_attest=A}sofia/internal/+15553214323@%s:53060", local_ip_v4), timeout_sec, NULL, NULL, NULL, NULL, NULL, SOF_NONE, NULL, NULL); fst_check(status == SWITCH_STATUS_SUCCESS); - fst_requires(session); - channel = switch_core_session_get_channel(session); - switch_channel_hangup(channel, SWITCH_CAUSE_NORMAL_CLEARING); - switch_core_session_rwunlock(session); - switch_sleep(10 * 1000 * 1000); + fst_check(session); + if (session) { + channel = switch_core_session_get_channel(session); + switch_channel_hangup(channel, SWITCH_CAUSE_NORMAL_CLEARING); + switch_core_session_rwunlock(session); + switch_sleep(10 * 1000 * 1000); + } } FST_TEST_END() +#endif FST_MODULE_END() diff --git a/src/mod/endpoints/mod_unicall/mod_unicall.c b/src/mod/endpoints/mod_unicall/mod_unicall.c index 92dee3f2cf..ee4d65e9ef 100644 --- a/src/mod/endpoints/mod_unicall/mod_unicall.c +++ b/src/mod/endpoints/mod_unicall/mod_unicall.c @@ -1771,7 +1771,7 @@ static switch_status_t config_unicall(int reload) for (i = min_span; i <= max_span; i++) { current_span = i; - if (current_span <= 0 || current_span > MAX_SPANS) { + if (current_span <= 0 || current_span >= MAX_SPANS) { switch_log_printf(SWITCH_CHANNEL_LOG, SWITCH_LOG_WARNING, "Invalid SPAN %d!\n", current_span); current_span = 0; continue; diff --git a/src/mod/endpoints/mod_verto/Makefile.am b/src/mod/endpoints/mod_verto/Makefile.am index dd54a32ee4..8951fe5e54 100644 --- a/src/mod/endpoints/mod_verto/Makefile.am +++ b/src/mod/endpoints/mod_verto/Makefile.am @@ -1,11 +1,12 @@ include $(top_srcdir)/build/modmake.rulesam MODNAME=mod_verto +if HAVE_KS mod_LTLIBRARIES = mod_verto.la -mod_verto_la_SOURCES = mod_verto.c ws.c mcast/mcast.c -mod_verto_la_CFLAGS = -D__EXTENSIONS__ -D_GNU_SOURCE $(AM_CFLAGS) +mod_verto_la_SOURCES = mod_verto.c mcast/mcast.c +mod_verto_la_CFLAGS = -D__EXTENSIONS__ -D_GNU_SOURCE $(AM_CFLAGS) $(KS_CFLAGS) mod_verto_la_CPPFLAGS = -I. -I$(switch_srcdir)/src/mod/endpoints/mod_verto/mcast -mod_verto_la_LIBADD = $(switch_builddir)/libfreeswitch.la +mod_verto_la_LIBADD = $(switch_builddir)/libfreeswitch.la $(KS_LIBS) mod_verto_la_LDFLAGS = -avoid-version -module -no-undefined -shared if HAVE_PERL @@ -25,7 +26,7 @@ MCAST_la_LDFLAGS = -avoid-version -module -no-undefined -shared $(PERL_LDFLAGS endif mcast/mcast_wrap.cpp: - cd mcast && swig -module MCAST -shadow -perl5 -c++ -DMULTIPLICITY -I../src/include -o mcast_wrap.cpp MCAST.i + cd mcast && swig -module MCAST -shadow -perl5 -c++ -DMULTIPLICITY -I../src/include -o mcast_wrap.cpp MCAST.i && patch -s -p0 -i hack.diff mcast/perlxsi.c: $(PERL) -MExtUtils::Embed -e xsinit -- -o mcast/perlxsi.c @@ -37,3 +38,10 @@ swigclean: rm -f mcast/mcast_wrap.* mcast/MCAST.so mcast/MCAST.pm mcast/perlxsi.* reswig: swigclean mcast/mcast_wrap.cpp mcast/perlxsi.c +else +install: error +all: error +error: + $(error You must install libks to build mod_verto) +endif + diff --git a/src/mod/endpoints/mod_verto/mcast/hack.diff b/src/mod/endpoints/mod_verto/mcast/hack.diff new file mode 100644 index 0000000000..578a60bd90 --- /dev/null +++ b/src/mod/endpoints/mod_verto/mcast/hack.diff @@ -0,0 +1,29 @@ +--- mcast_wrap.cpp.old 2015-06-16 12:27:19.024000000 -0500 ++++ mcast_wrap.cpp 2015-06-16 12:34:51.540000000 -0500 +@@ -1965,7 +1965,7 @@ XS(_wrap_McastHandle_send) { + SWIG_exception_fail(SWIG_ArgError(res2), "in method '" "McastHandle_send" "', argument " "2"" of type '" "char const *""'"); + } + arg2 = reinterpret_cast< char * >(buf2); +- assert(arg1); ++ if (!arg1) SWIG_exception_fail(SWIG_ValueError, "in method '" "McastHandle_send" "', argument " "1"" is NULL"); + result = (int)(arg1)->send((char const *)arg2); + ST(argvi) = SWIG_From_int SWIG_PERL_CALL_ARGS_1(static_cast< int >(result)); argvi++ ; + +@@ -2006,7 +2006,7 @@ XS(_wrap_McastHandle_recv) { + } + arg2 = static_cast< int >(val2); + } +- assert(arg1); ++ if (!arg1) SWIG_exception_fail(SWIG_ValueError, "in method '" "McastHandle_recv" "', argument " "1"" is NULL"); + result = (char *)(arg1)->recv(arg2); + ST(argvi) = SWIG_FromCharPtr((const char *)result); argvi++ ; + +@@ -2037,7 +2037,7 @@ XS(_wrap_McastHandle_filenum) { + SWIG_exception_fail(SWIG_ArgError(res1), "in method '" "McastHandle_filenum" "', argument " "1"" of type '" "McastHandle *""'"); + } + arg1 = reinterpret_cast< McastHandle * >(argp1); +- assert(arg1); ++ if (!arg1) SWIG_exception_fail(SWIG_ValueError, "in method '" "McastHandle_filenum" "', argument " "1"" is NULL"); + result = (arg1)->filenum(); + ST(argvi) = SWIG_NewPointerObj((new mcast_socket_t(static_cast< const mcast_socket_t& >(result))), SWIGTYPE_p_mcast_socket_t, SWIG_POINTER_OWN | 0); argvi++ ; + diff --git a/src/mod/endpoints/mod_verto/mcast/mcast_wrap.cpp b/src/mod/endpoints/mod_verto/mcast/mcast_wrap.cpp index 5473788de7..7a1eb92c89 100644 --- a/src/mod/endpoints/mod_verto/mcast/mcast_wrap.cpp +++ b/src/mod/endpoints/mod_verto/mcast/mcast_wrap.cpp @@ -1965,6 +1965,7 @@ XS(_wrap_McastHandle_send) { SWIG_exception_fail(SWIG_ArgError(res2), "in method '" "McastHandle_send" "', argument " "2"" of type '" "char const *""'"); } arg2 = reinterpret_cast< char * >(buf2); + if (!arg1) SWIG_exception_fail(SWIG_ValueError, "in method '" "McastHandle_send" "', argument " "1"" is NULL"); result = (int)(arg1)->send((char const *)arg2); ST(argvi) = SWIG_From_int SWIG_PERL_CALL_ARGS_1(static_cast< int >(result)); argvi++ ; @@ -2005,6 +2006,7 @@ XS(_wrap_McastHandle_recv) { } arg2 = static_cast< int >(val2); } + if (!arg1) SWIG_exception_fail(SWIG_ValueError, "in method '" "McastHandle_recv" "', argument " "1"" is NULL"); result = (char *)(arg1)->recv(arg2); ST(argvi) = SWIG_FromCharPtr((const char *)result); argvi++ ; @@ -2035,6 +2037,7 @@ XS(_wrap_McastHandle_filenum) { SWIG_exception_fail(SWIG_ArgError(res1), "in method '" "McastHandle_filenum" "', argument " "1"" of type '" "McastHandle *""'"); } arg1 = reinterpret_cast< McastHandle * >(argp1); + if (!arg1) SWIG_exception_fail(SWIG_ValueError, "in method '" "McastHandle_filenum" "', argument " "1"" is NULL"); result = (arg1)->filenum(); ST(argvi) = SWIG_NewPointerObj((new mcast_socket_t(static_cast< const mcast_socket_t& >(result))), SWIGTYPE_p_mcast_socket_t, SWIG_POINTER_OWN | 0); argvi++ ; diff --git a/src/mod/endpoints/mod_verto/mod_verto.2017.vcxproj b/src/mod/endpoints/mod_verto/mod_verto.2017.vcxproj index 3b82a87672..ff3b53037f 100644 --- a/src/mod/endpoints/mod_verto/mod_verto.2017.vcxproj +++ b/src/mod/endpoints/mod_verto/mod_verto.2017.vcxproj @@ -47,6 +47,7 @@ + @@ -135,12 +136,6 @@ - - 6386;4267;4244;6031;6340;6246;6011;6387;%(DisableSpecificWarnings) - 6386;4267;4244;6031;6340;6246;6011;6387;%(DisableSpecificWarnings) - 6386;4267;4244;6031;6340;6246;6011;6387;%(DisableSpecificWarnings) - 6386;4267;4244;6031;6340;6246;6011;6387;%(DisableSpecificWarnings) - diff --git a/src/mod/endpoints/mod_verto/mod_verto.c b/src/mod/endpoints/mod_verto/mod_verto.c index 342ed8b26e..8b69519f6f 100644 --- a/src/mod/endpoints/mod_verto/mod_verto.c +++ b/src/mod/endpoints/mod_verto/mod_verto.c @@ -33,7 +33,6 @@ #include #include - /* Prototypes */ SWITCH_MODULE_SHUTDOWN_FUNCTION(mod_verto_shutdown); SWITCH_MODULE_LOAD_FUNCTION(mod_verto_load); @@ -41,11 +40,11 @@ SWITCH_MODULE_RUNTIME_FUNCTION(mod_verto_runtime); SWITCH_MODULE_DEFINITION(mod_verto, mod_verto_load, mod_verto_shutdown, mod_verto_runtime); +#define HTTP_CHUNK_SIZE 1024 * 32 #define EP_NAME "verto.rtc" //#define WSS_STANDALONE 1 -#include "ws.h" +#include "ks.h" -////////////////////////// #include #ifndef WIN32 #include @@ -151,21 +150,21 @@ static void verto_deinit_ssl(verto_profile_t *profile) } } -static void close_file(ws_socket_t *sock) +static void close_file(ks_socket_t *sock) { - if (*sock != ws_sock_invalid) { + if (*sock != KS_SOCK_INVALID) { #ifndef WIN32 close(*sock); #else closesocket(*sock); #endif - *sock = ws_sock_invalid; + *sock = KS_SOCK_INVALID; } } -static void close_socket(ws_socket_t *sock) +static void close_socket(ks_socket_t *sock) { - if (*sock != ws_sock_invalid) { + if (*sock != KS_SOCK_INVALID) { shutdown(*sock, 2); close_file(sock); } @@ -294,7 +293,7 @@ static uint32_t jsock_unsub_head(jsock_t *jsock, jsock_sub_node_head_t *head) } if (thisnp->jsock->profile->debug || verto_globals.debug) { - switch_log_printf(SWITCH_CHANNEL_LOG, SWITCH_LOG_DEBUG, "UNSUBBING %s [%s]\n", thisnp->jsock->name, thisnp->head->event_channel); + switch_log_printf(SWITCH_CHANNEL_LOG, verto_globals.debug_level, "UNSUBBING %s [%s]\n", thisnp->jsock->name, thisnp->head->event_channel); } thisnp->jsock = NULL; @@ -603,12 +602,12 @@ static switch_ssize_t ws_write_json(jsock_t *jsock, cJSON **json, switch_bool_t if ((json_text = cJSON_PrintUnformatted(*json))) { if (jsock->profile->debug || verto_globals.debug) { - char *log_text = cJSON_Print(*json); - switch_log_printf(SWITCH_CHANNEL_LOG, SWITCH_LOG_DEBUG, "WRITE %s [%s]\n", jsock->name, log_text); - free(log_text); + //char *log_text = cJSON_Prin(*json); + switch_log_printf(SWITCH_CHANNEL_LOG, verto_globals.debug_level, "WRITE %s [%s]\n", jsock->name, json_text); + //free(log_text); } switch_mutex_lock(jsock->write_mutex); - r = ws_write_frame(&jsock->ws, WSOC_TEXT, json_text, strlen(json_text)); + r = kws_write_frame(jsock->ws, WSOC_TEXT, json_text, strlen(json_text)); switch_mutex_unlock(jsock->write_mutex); switch_safe_free(json_text); } @@ -664,7 +663,8 @@ static switch_status_t jsock_queue_event(jsock_t *jsock, cJSON **json, switch_bo return status; } -static void write_event(const char *event_channel, jsock_t *use_jsock, cJSON *event) +static switch_bool_t event_channel_check_auth(jsock_t *jsock, const char *event_channel); +static void write_event(const char *event_channel, const char *super_channel, jsock_t *use_jsock, cJSON *event) { jsock_sub_node_head_t *head; @@ -673,11 +673,43 @@ static void write_event(const char *event_channel, jsock_t *use_jsock, cJSON *ev for(np = head->node; np; np = np->next) { cJSON *msg = NULL, *params; - + if (!use_jsock || use_jsock == np->jsock) { + const char *visibility; + //char *tmp; + + if ((visibility = cJSON_GetObjectCstr(event, "contentVisibility"))) { + if (strcasecmp(visibility, "public") && (np->jsock->id && !strncasecmp(np->jsock->id, "guest", 5))) { + int perm = 0; + + perm = event_channel_check_auth(np->jsock, event_channel); + + if (!perm && super_channel) { + perm = event_channel_check_auth(np->jsock, super_channel); + } + + if (!perm) { + perm = switch_event_channel_permission_verify(np->jsock->uuid_str, event_channel); + } + + if (!perm && super_channel) { + perm = switch_event_channel_permission_verify(np->jsock->uuid_str, super_channel); + } + + if (!perm) { + continue; + } + } + } + //tmp = cJSON_Print(event); + //printf("%s\n", tmp); + //free(tmp); + params = cJSON_Duplicate(event, 1); cJSON_AddItemToObject(params, "eventSerno", cJSON_CreateNumber(np->serno++)); + cJSON_AddItemToObject(params, "subscribedChannel", cJSON_CreateString(head->event_channel)); msg = jrpc_new_req("verto.event", NULL, ¶ms); + jsock_queue_event(np->jsock, &msg, SWITCH_TRUE); } } @@ -687,7 +719,7 @@ static void write_event(const char *event_channel, jsock_t *use_jsock, cJSON *ev static void jsock_send_event(cJSON *event) { - const char *event_channel, *session_uuid = NULL; + const char *event_channel, *session_uuid = NULL, *direct_id = NULL; jsock_t *use_jsock = NULL; switch_core_session_t *session = NULL; @@ -696,17 +728,27 @@ static void jsock_send_event(cJSON *event) return; } - - if ((session = switch_core_session_locate(event_channel))) { - switch_channel_t *channel = switch_core_session_get_channel(session); - const char *jsock_uuid_str = switch_channel_get_variable(channel, "jsock_uuid_str"); - if (jsock_uuid_str) { - use_jsock = get_jsock(jsock_uuid_str); - } - switch_core_session_rwunlock(session); + if (!(direct_id = cJSON_GetObjectCstr(event, "eventChannelSessid"))) { + direct_id = event_channel; } - if (use_jsock || (use_jsock = get_jsock(event_channel))) { /* implicit subscription to channel identical to the connection uuid or session uuid */ + if ((session_uuid = cJSON_GetObjectCstr(event, "sessid"))) { + if (!(use_jsock = get_jsock(session_uuid))) { + switch_log_printf(SWITCH_CHANNEL_LOG, SWITCH_LOG_WARNING, "Socket %s not connected\n", session_uuid); + return; + } + } else { + if ((session = switch_core_session_locate(direct_id))) { + switch_channel_t *channel = switch_core_session_get_channel(session); + const char *jsock_uuid_str = switch_channel_get_variable(channel, "jsock_uuid_str"); + if (jsock_uuid_str) { + use_jsock = get_jsock(jsock_uuid_str); + } + switch_core_session_rwunlock(session); + } + } + + if (use_jsock || (use_jsock = get_jsock(direct_id))) { /* implicit subscription to channel identical to the connection uuid or session uuid */ cJSON *msg = NULL, *params; params = cJSON_Duplicate(event, 1); msg = jrpc_new_req("verto.event", NULL, ¶ms); @@ -716,23 +758,15 @@ static void jsock_send_event(cJSON *event) return; } - - if ((session_uuid = cJSON_GetObjectCstr(event, "sessid"))) { - if (!(use_jsock = get_jsock(session_uuid))) { - switch_log_printf(SWITCH_CHANNEL_LOG, SWITCH_LOG_WARNING, "Socket %s not connected\n", session_uuid); - return; - } - } - switch_thread_rwlock_rdlock(verto_globals.event_channel_rwlock); - write_event(event_channel, use_jsock, event); + write_event(event_channel, NULL, use_jsock, event); if (strchr(event_channel, '.')) { char *main_channel = strdup(event_channel); char *p; switch_assert(main_channel); p = strchr(main_channel, '.'); if (p) *p = '\0'; - write_event(main_channel, use_jsock, event); + write_event(main_channel, event_channel, use_jsock, event); free(main_channel); } switch_thread_rwlock_unlock(verto_globals.event_channel_rwlock); @@ -789,7 +823,7 @@ static void jrpc_add_func(const char *method, jrpc_func_t func) static char *MARKER = "X"; -static void set_perm(const char *str, switch_event_t **event) +static void set_perm(const char *str, switch_event_t **event, switch_bool_t add) { char delim = ','; char *cur, *next; @@ -802,8 +836,10 @@ static void set_perm(const char *str, switch_event_t **event) } } - switch_event_create(event, SWITCH_EVENT_REQUEST_PARAMS); - + if (event && !*event) { + switch_event_create(event, SWITCH_EVENT_REQUEST_PARAMS); + } + if (!zstr(str)) { edup = strdup(str); switch_assert(edup); @@ -817,8 +853,12 @@ static void set_perm(const char *str, switch_event_t **event) *next++ = '\0'; } - switch_event_add_header_string(*event, SWITCH_STACK_BOTTOM, cur, MARKER); - + if (add) { + switch_event_add_header_string(*event, SWITCH_STACK_BOTTOM, cur, MARKER); + } else { + switch_event_del_header(*event, cur); + } + cur = next; } @@ -860,15 +900,41 @@ static void check_permissions(jsock_t *jsock, switch_xml_t x_user, cJSON *params } - set_perm(allowed_methods, &jsock->allowed_methods); - set_perm(allowed_jsapi, &jsock->allowed_jsapi); - set_perm(allowed_fsapi, &jsock->allowed_fsapi); - set_perm(allowed_event_channels, &jsock->allowed_event_channels); + set_perm(allowed_methods, &jsock->allowed_methods, SWITCH_TRUE); + set_perm(allowed_jsapi, &jsock->allowed_jsapi, SWITCH_TRUE); + set_perm(allowed_fsapi, &jsock->allowed_fsapi, SWITCH_TRUE); + set_perm(allowed_event_channels, &jsock->allowed_event_channels, SWITCH_TRUE); switch_event_add_header_string(jsock->allowed_methods, SWITCH_STACK_BOTTOM, "login", MARKER); } +static switch_status_t add_perm(const char *sessid, const char *type, const char *value, switch_bool_t add) +{ + jsock_t *jsock = NULL; + switch_status_t status = SWITCH_STATUS_FALSE; + + if (type && value && (jsock = get_jsock(sessid))) { + status = SWITCH_STATUS_SUCCESS; + + if (!strcmp(type, "methods")) { + set_perm(value, &jsock->allowed_methods, add); + } else if (!strcmp(type, "jsapi")) { + set_perm(value, &jsock->allowed_jsapi, add); + } else if (!strcmp(type, "fsapi")) { + set_perm(value, &jsock->allowed_fsapi, add); + } else if (!strcmp(type, "event_channels")) { + set_perm(value, &jsock->allowed_event_channels, add); + } else { + status = SWITCH_STATUS_FALSE; + } + + switch_thread_rwlock_unlock(jsock->rwlock); + } + + return status; +} + static void login_fire_custom_event(jsock_t *jsock, cJSON *params, int success, const char *result_txt) { switch_event_t *s_event; @@ -937,10 +1003,10 @@ static switch_bool_t check_auth(jsock_t *jsock, cJSON *params, int *code, char * } else if (switch_true(jsock->profile->userauth)) { id = switch_core_strdup(jsock->pool, login); - if ((domain = strchr(id, '@'))) { + if (jsock->profile->chop_domain && (domain = strchr(id, '@'))) { *domain++ = '\0'; } - + } if (jsock->profile->register_domain) { @@ -973,7 +1039,8 @@ static switch_bool_t check_auth(jsock_t *jsock, cJSON *params, int *code, char * if ((json_ptr = cJSON_GetObjectItem(params, "userVariables"))) { cJSON * i; - + + switch_mutex_lock(jsock->flag_mutex); for(i = json_ptr->child; i; i = i->next) { if (i->type == cJSON_True) { switch_event_add_header_string(jsock->user_vars, SWITCH_STACK_BOTTOM, i->string, "true"); @@ -983,18 +1050,28 @@ static switch_bool_t check_auth(jsock_t *jsock, cJSON *params, int *code, char * switch_event_add_header_string(jsock->user_vars, SWITCH_STACK_BOTTOM, i->string, i->valuestring); } } + switch_mutex_unlock(jsock->flag_mutex); } + if (jsock->profile->send_passwd || verto_globals.send_passwd) { + switch_event_add_header_string(req_params, SWITCH_STACK_BOTTOM, "user_supplied_pass", passwd); + } + switch_event_add_header_string(req_params, SWITCH_STACK_BOTTOM, "action", "jsonrpc-authenticate"); if (switch_xml_locate_user_merged("id", id, domain, NULL, &x_user, req_params) != SWITCH_STATUS_SUCCESS && !jsock->profile->blind_reg) { *code = CODE_AUTH_FAILED; switch_snprintf(message, mlen, "Login Incorrect"); login_fire_custom_event(jsock, params, 0, "Login Incorrect"); + switch_log_printf(SWITCH_CHANNEL_LOG, SWITCH_LOG_WARNING, "Login incorrect for user: %s domain: %s\n", id, domain ? domain : "N/A"); } else { switch_xml_t x_param, x_params; const char *use_passwd = NULL, *verto_context = NULL, *verto_dialplan = NULL; + time_t now = switch_epoch_time_now(NULL); + switch_log_printf(SWITCH_CHANNEL_LOG, SWITCH_LOG_WARNING, "Login sucessful for user: %s domain: %s\n", id, domain ? domain : "N/A"); + + jsock->logintime = now; jsock->id = switch_core_strdup(jsock->pool, id); jsock->domain = switch_core_strdup(jsock->pool, domain); jsock->uid = switch_core_sprintf(jsock->pool, "%s@%s", id, domain); @@ -1037,7 +1114,24 @@ static switch_bool_t check_auth(jsock_t *jsock, cJSON *params, int *code, char * const char *var = switch_xml_attr_soft(x_param, "name"); const char *val = switch_xml_attr_soft(x_param, "value"); + switch_mutex_lock(jsock->flag_mutex); switch_event_add_header_string(jsock->vars, SWITCH_STACK_BOTTOM, var, val); + switch_event_add_header_string(jsock->user_vars, SWITCH_STACK_BOTTOM, var, val); + switch_mutex_unlock(jsock->flag_mutex); + + switch_clear_flag(jsock, JPFLAG_AUTH_EXPIRED); + + if (!strcmp(var, "login-expires")) { + uint32_t tmp = atol(val); + + if (tmp > now) { + jsock->exptime = tmp; + switch_log_printf(SWITCH_CHANNEL_LOG, SWITCH_LOG_DEBUG, "Login expire time for %s set to %ld seconds [%ld] [%ld]\n", jsock->uid, tmp - now, jsock->exptime, now); + } else { + switch_log_printf(SWITCH_CHANNEL_LOG, SWITCH_LOG_WARNING, "Invalid expire time for %s. Defaulting to 300 sec\n", jsock->uid); + jsock->exptime = now + 300; + } + } } } @@ -1050,12 +1144,13 @@ static switch_bool_t check_auth(jsock_t *jsock, cJSON *params, int *code, char * } - if (zstr(use_passwd) || strcmp(a1_hash ? a1_hash : passwd, use_passwd)) { + if (!use_passwd || zstr(use_passwd) || strcmp(a1_hash ? a1_hash : passwd, use_passwd)) { r = SWITCH_FALSE; *code = CODE_AUTH_FAILED; switch_snprintf(message, mlen, "Authentication Failure"); jsock->uid = NULL; login_fire_custom_event(jsock, params, 0, "Authentication Failure"); + switch_xml_clear_user_cache("id", id, domain); } else { switch_log_printf(SWITCH_CHANNEL_LOG, SWITCH_LOG_DEBUG,"auth using %s\n",a1_hash ? "a1-hash" : "username & password"); r = SWITCH_TRUE; @@ -1124,6 +1219,8 @@ static jsock_t *get_jsock(const char *uuid) return jsock; } +static void tech_reattach(verto_pvt_t *tech_pvt, jsock_t *jsock); + static void attach_jsock(jsock_t *jsock) { jsock_t *jp; @@ -1143,9 +1240,11 @@ static void attach_jsock(jsock_t *jsock) switch_log_printf(SWITCH_CHANNEL_LOG, SWITCH_LOG_WARNING, "New connection for session %s dropping previous connection.\n", jsock->uuid_str); switch_core_hash_delete(verto_globals.jsock_hash, jsock->uuid_str); ws_write_json(jp, &msg, SWITCH_TRUE); + detach_calls(jp); cJSON_Delete(msg); jp->nodelete = 1; jp->drop = 1; + jsock->attach_timer = 5; } } @@ -1194,6 +1293,22 @@ static int attach_wake(void) return 0; } +static void add_variables(verto_pvt_t *tech_pvt, cJSON *params) +{ + cJSON *jvariables = NULL; + switch_event_header_t *hi; + switch_event_t *variables; + + jvariables = cJSON_CreateObject(); + switch_channel_get_variables_prefix(tech_pvt->channel, "verto_svar_", &variables); + for (hi = variables->headers; hi; hi = hi->next) { + cJSON_AddItemToObject(jvariables, hi->name, cJSON_CreateString(hi->value)); + } + cJSON_AddItemToObject(params, "variables", jvariables); + switch_event_destroy(&variables); +} + + static void tech_reattach(verto_pvt_t *tech_pvt, jsock_t *jsock) { cJSON *params = NULL; @@ -1205,6 +1320,9 @@ static void tech_reattach(verto_pvt_t *tech_pvt, jsock_t *jsock) switch_set_flag(tech_pvt, TFLAG_ATTACH_REQ); msg = jrpc_new_req("verto.attach", tech_pvt->call_id, ¶ms); + add_variables(tech_pvt, params); + + switch_channel_set_flag(tech_pvt->channel, CF_REATTACHED); switch_channel_set_flag(tech_pvt->channel, CF_REINVITE); switch_channel_set_flag(tech_pvt->channel, CF_RECOVERING); switch_core_media_gen_local_sdp(tech_pvt->session, SDP_TYPE_REQUEST, NULL, 0, NULL, 0); @@ -1217,6 +1335,8 @@ static void tech_reattach(verto_pvt_t *tech_pvt, jsock_t *jsock) switch_channel_get_name(tech_pvt->channel), tech_pvt->mparams->local_sdp_str); set_call_params(params, tech_pvt); + switch_core_media_gen_key_frame(tech_pvt->session); + switch_channel_set_flag(tech_pvt->channel, CF_VIDEO_REFRESH_REQ); jsock_queue_event(jsock, &msg, SWITCH_TRUE); } @@ -1232,7 +1352,16 @@ static void drop_detached(void) } if (tech_pvt->detach_time && (now - tech_pvt->detach_time) > verto_globals.detach_timeout) { - switch_channel_hangup(tech_pvt->channel, SWITCH_CAUSE_RECOVERY_ON_TIMER_EXPIRE); + jsock_t *jsock = NULL; + + if ((jsock = get_jsock(tech_pvt->jsock_uuid))) { + if (switch_test_flag(jsock, JPFLAG_AUTH_EXPIRED)) { + switch_channel_hangup(tech_pvt->channel, SWITCH_CAUSE_BEARERCAPABILITY_NOTAUTH); + } + switch_thread_rwlock_unlock(jsock->rwlock); + } else { + switch_channel_hangup(tech_pvt->channel, SWITCH_CAUSE_RECOVERY_ON_TIMER_EXPIRE); + } } } switch_thread_rwlock_unlock(verto_globals.tech_rwlock); @@ -1255,7 +1384,7 @@ static void attach_calls(jsock_t *jsock) } tech_reattach(tech_pvt, jsock); - cJSON_AddItemToArray(reattached_sessions, cJSON_CreateString(jsock->uuid_str)); + cJSON_AddItemToArray(reattached_sessions, cJSON_CreateString(switch_core_session_get_uuid(tech_pvt->session))); } } switch_thread_rwlock_unlock(verto_globals.tech_rwlock); @@ -1282,7 +1411,7 @@ static void detach_calls(jsock_t *jsock) continue; } - if (switch_channel_test_flag(tech_pvt->channel, CF_VIDEO_ONLY)) { + if (switch_channel_test_flag(tech_pvt->channel, CF_NO_RECOVER)) { switch_channel_hangup(tech_pvt->channel, SWITCH_CAUSE_NORMAL_CLEARING); continue; } @@ -1355,7 +1484,7 @@ static cJSON *process_jrpc(jsock_t *jsock, cJSON *json) jrpc_add_id(reply, id, "", 0); - if (!switch_test_flag(jsock, JPFLAG_AUTHED) && (jsock->profile->userauth || jsock->profile->root_passwd)) { + if ((!switch_test_flag(jsock, JPFLAG_AUTHED) || (method && !strcmp(method, "login"))) && (jsock->profile->userauth || jsock->profile->root_passwd)) { int code = CODE_AUTH_REQUIRED; char message[128] = "Authentication Required"; @@ -1410,8 +1539,8 @@ static switch_status_t process_input(jsock_t *jsock, uint8_t *data, switch_ssize if (json) { if (jsock->profile->debug || verto_globals.debug) { - char *log_text = cJSON_Print(json); - switch_log_printf(SWITCH_CHANNEL_LOG, SWITCH_LOG_DEBUG, "READ %s [%s]\n", jsock->name, log_text); + char *log_text = cJSON_PrintUnformatted(json); + switch_log_printf(SWITCH_CHANNEL_LOG, verto_globals.debug_level, "READ %s [%s]\n", jsock->name, log_text); free(log_text); } @@ -1462,52 +1591,36 @@ static void jsock_check_event_queue(jsock_t *jsock) /* DO NOT use this unless you know what you are doing, you are WARNNED!!! */ static uint8_t *http_stream_read(switch_stream_handle_t *handle, int *len) { - switch_http_request_t *r = (switch_http_request_t *) handle->data; + kws_request_t *r = (kws_request_t *) handle->data; jsock_t *jsock = r->user_data; - wsh_t *wsh = &jsock->ws; + kws_t *wsh = jsock->ws; + uint8_t *buffer = NULL; if (!jsock->profile->running) { *len = 0; return NULL; } - *len = (int)(r->bytes_buffered - r->bytes_read); - - if (*len > 0) { // we already read part of the body - uint8_t *data = (uint8_t *)wsh->buffer + r->bytes_read; - r->bytes_read = r->bytes_buffered; - return data; - } - - if (r->content_length && (r->bytes_read - r->bytes_header) >= r->content_length) { + *len = HTTP_CHUNK_SIZE; + if ((*len = (int)kws_read_buffer(wsh, &buffer, *len, 1)) < 0) { *len = 0; return NULL; } - *len = (int)(r->content_length - (r->bytes_read - r->bytes_header)); - *len = *len > sizeof(wsh->buffer) ? wsh->buflen : *len; - - if ((*len = (int)ws_raw_read(wsh, wsh->buffer, *len, wsh->block)) < 0) { - *len = 0; - return NULL; - } - - r->bytes_read += *len; - - return (uint8_t *)wsh->buffer; + return buffer; } static switch_status_t http_stream_raw_write(switch_stream_handle_t *handle, uint8_t *data, switch_size_t datalen) { - switch_http_request_t *r = (switch_http_request_t *) handle->data; + kws_request_t *r = (kws_request_t *) handle->data; jsock_t *jsock = r->user_data; - return ws_raw_write(&jsock->ws, data, (uint32_t)datalen) ? SWITCH_STATUS_SUCCESS : SWITCH_STATUS_FALSE; + return kws_raw_write(jsock->ws, data, (uint32_t)datalen) ? SWITCH_STATUS_SUCCESS : SWITCH_STATUS_FALSE; } static switch_status_t http_stream_write(switch_stream_handle_t *handle, const char *fmt, ...) { - switch_http_request_t *r = (switch_http_request_t *) handle->data; + kws_request_t *r = (kws_request_t *) handle->data; jsock_t *jsock = r->user_data; int ret = 1; char *data; @@ -1519,7 +1632,7 @@ static switch_status_t http_stream_write(switch_stream_handle_t *handle, const c if (data) { if (ret) { - ret =(int) ws_raw_write(&jsock->ws, data, (uint32_t)strlen(data)); + ret =(int) kws_raw_write(jsock->ws, data, (uint32_t)strlen(data)); } switch_safe_free(data); } @@ -1527,7 +1640,7 @@ static switch_status_t http_stream_write(switch_stream_handle_t *handle, const c return ret ? SWITCH_STATUS_SUCCESS : SWITCH_STATUS_FALSE; } -static void http_static_handler(switch_http_request_t *request, verto_vhost_t *vhost) +static void http_static_handler(kws_request_t *request, verto_vhost_t *vhost) { jsock_t *jsock = request->user_data; char path[512]; @@ -1535,11 +1648,16 @@ static void http_static_handler(switch_http_request_t *request, verto_vhost_t *v char *ext; uint8_t chunk[4096]; const char *mime_type = "text/html", *new_type; + switch_time_exp_t tm; + char date[80] = ""; + switch_time_t ts = switch_micro_time_now(); + switch_time_exp_lt(&tm, ts); + switch_rfc822_date(date, ts); if (strncmp(request->method, "GET", 3) && strncmp(request->method, "HEAD", 4)) { char *data = "HTTP/1.1 415 Method Not Allowed\r\n" "Content-Length: 0\r\n\r\n"; - ws_raw_write(&jsock->ws, data, strlen(data)); + kws_raw_write(jsock->ws, data, strlen(data)); return; } @@ -1569,12 +1687,12 @@ static void http_static_handler(switch_http_request_t *request, verto_vhost_t *v "Server: FreeSWITCH-%s-mod_verto\r\n" "Content-Type: %s\r\n" "Content-Length: %" SWITCH_SIZE_T_FMT "\r\n\r\n", - switch_event_get_header(request->headers, "Event-Date-GMT"), + date, switch_version_full(), mime_type, flen); - ws_raw_write(&jsock->ws, chunk, strlen((char *)chunk)); + kws_raw_write(jsock->ws, chunk, strlen((char *)chunk)); for (;;) { switch_status_t status; @@ -1586,42 +1704,49 @@ static void http_static_handler(switch_http_request_t *request, verto_vhost_t *v break; } - ws_raw_write(&jsock->ws, chunk, flen); + kws_raw_write(jsock->ws, chunk, flen); } switch_file_close(fd); } else { char *data = "HTTP/1.1 404 Not Found\r\n" "Content-Length: 0\r\n\r\n"; - ws_raw_write(&jsock->ws, data, strlen(data)); + kws_raw_write(jsock->ws, data, strlen(data)); + } +} + +static void request_headers_to_event(switch_event_t *event, kws_request_t *request) +{ + int i; + + for (i = 0; i < KWS_MAX_HEADERS; i++) { + if (!request->headers_k[i]) break; + switch_event_add_header_string(event, SWITCH_STACK_BOTTOM, request->headers_k[i], request->headers_v[i]); } } static void http_run(jsock_t *jsock) { - switch_http_request_t request = { 0 }; + kws_request_t *request = NULL; switch_stream_handle_t stream = { 0 }; char *err = NULL; char *ext; verto_vhost_t *vhost; - switch_bool_t keepalive; + ks_bool_t keepalive; new_req: - - request.user_data = jsock; - if (switch_event_create(&stream.param_event, SWITCH_EVENT_CHANNEL_DATA) != SWITCH_STATUS_SUCCESS) { goto err; } - request.headers = stream.param_event; - if (switch_http_parse_header(jsock->ws.buffer, (uint32_t)jsock->ws.datalen, &request) != SWITCH_STATUS_SUCCESS) { - switch_event_destroy(&stream.param_event); + if (kws_parse_header(jsock->ws, &request) != KS_STATUS_SUCCESS) { goto err; } - switch_log_printf(SWITCH_CHANNEL_LOG, SWITCH_LOG_DEBUG, "%s [%4" SWITCH_SIZE_T_FMT "] %s\n", jsock->name, jsock->ws.datalen, request.uri); + request->user_data = jsock; - if (!strncmp(request.method, "OPTIONS", 7)) { + switch_log_printf(SWITCH_CHANNEL_LOG, SWITCH_LOG_DEBUG, "%s %s\n", jsock->name, request->uri); + + if (!strncmp(request->method, "OPTIONS", 7)) { char data[512]; switch_snprintf(data, sizeof(data), "HTTP/1.1 200 OK\r\n" @@ -1629,23 +1754,32 @@ new_req: "Date: %s\r\n" "Allow: HEAD,GET,POST,PUT,DELETE,PATCH,OPTIONS\r\n" "Server: FreeSWITCH-%s-mod_verto\r\n\r\n", - switch_event_get_header(request.headers, "Event-Date-GMT"), + switch_event_get_header(stream.param_event, "Event-Date-GMT"), switch_version_full()); - ws_raw_write(&jsock->ws, data, strlen(data)); + kws_raw_write(jsock->ws, data, strlen(data)); goto done; } - if (!strncmp(request.method, "POST", 4) && request.content_length && request.content_type && - !strncmp(request.content_type, "application/x-www-form-urlencoded", 33)) { + if (request->content_length && request->content_length > INT32_MAX) { + char *data = "HTTP/1.1 413 Request Entity Too Large\r\n" + "Content-Length: 0\r\n\r\n"; + kws_raw_write(jsock->ws, data, strlen(data)); + request->keepalive = 0; + goto done; + } + + if (!strncmp(request->method, "POST", 4) && request->content_length && request->content_type && + !strncmp(request->content_type, "application/x-www-form-urlencoded", 33)) { char *buffer = NULL; switch_ssize_t len = 0, bytes = 0; - if (request.content_length > 2 * 1024 * 1024 - 1) { + if (request->content_length && request->content_length > 10 * 1024 * 1024 - 1) { char *data = "HTTP/1.1 413 Request Entity Too Large\r\n" "Content-Length: 0\r\n\r\n"; - ws_raw_write(&jsock->ws, data, strlen(data)); + kws_raw_write(jsock->ws, data, strlen(data)); + request->keepalive = 0; goto done; } @@ -1653,14 +1787,12 @@ new_req: goto request_err; } - if ((bytes = request.bytes_buffered - request.bytes_read) > 0) { - memcpy(buffer, jsock->ws.buffer + request.bytes_read, bytes); - } + while(bytes < (switch_ssize_t)request->content_length) { + len = request->content_length - bytes; - while(bytes < (switch_ssize_t)request.content_length) { - len = request.content_length - bytes; +#define WS_BLOCK 1 - if ((len = ws_raw_read(&jsock->ws, buffer + bytes, len, jsock->ws.block)) < 0) { + if ((len = kws_raw_read(jsock->ws, buffer + bytes, len, WS_BLOCK)) < 0) { switch_log_printf(SWITCH_CHANNEL_LOG, SWITCH_LOG_ERROR, "Read error %" SWITCH_SSIZE_T_FMT"\n", len); goto done; } @@ -1670,19 +1802,20 @@ new_req: *(buffer + bytes) = '\0'; - switch_http_parse_qs(&request, buffer); + kws_parse_qs(request, buffer); free(buffer); } - // switch_http_dump_request(&request); + // kws_request_dump(request); - stream.data = &request; + stream.data = request; stream.read_function = http_stream_read; stream.write_function = http_stream_write; stream.raw_write_function = http_stream_raw_write; + request_headers_to_event(stream.param_event, request); - switch_event_add_header_string(request.headers, SWITCH_STACK_BOTTOM, "Request-Method", request.method); - switch_event_add_header_string(request.headers, SWITCH_STACK_BOTTOM, "HTTP-Request-URI", request.uri); + switch_event_add_header_string(stream.param_event, SWITCH_STACK_BOTTOM, "Request-Method", request->method); + switch_event_add_header_string(stream.param_event, SWITCH_STACK_BOTTOM, "HTTP-Request-URI", request->uri); if (!jsock->profile->vhosts) goto err; @@ -1693,11 +1826,11 @@ new_req: int code = CODE_AUTH_REQUIRED; char message[128] = "Authentication Required"; cJSON *params = NULL; - char *www_auth; + const char *www_auth; char auth_buffer[512]; char *auth_user = NULL, *auth_pass = NULL; - www_auth = switch_event_get_header(request.headers, "Authorization"); + www_auth = request->authorization; if (zstr(www_auth)) { switch_snprintf(auth_buffer, sizeof(auth_buffer), @@ -1705,7 +1838,7 @@ new_req: "WWW-Authenticate: Basic realm=\"%s\"\r\n" "Content-Length: 0\r\n\r\n", vhost->auth_realm); - ws_raw_write(&jsock->ws, auth_buffer, strlen(auth_buffer)); + kws_raw_write(jsock->ws, auth_buffer, strlen(auth_buffer)); goto done; } @@ -1740,7 +1873,7 @@ new_req: "WWW-Authenticate: Basic realm=\"%s\"\r\n" "Content-Length: 0\r\n\r\n", vhost->auth_realm); - ws_raw_write(&jsock->ws, auth_buffer, strlen(auth_buffer)); + kws_raw_write(jsock->ws, auth_buffer, strlen(auth_buffer)); cJSON_Delete(params); goto done; } else { @@ -1749,7 +1882,7 @@ new_req: authed: switch_set_flag(jsock, JPFLAG_AUTHED); - switch_event_add_header_string(request.headers, SWITCH_STACK_BOTTOM, "HTTP-USER", auth_user); + switch_event_add_header_string(stream.param_event, SWITCH_STACK_BOTTOM, "HTTP-USER", auth_user); } if (vhost->rewrites) { @@ -1761,10 +1894,10 @@ authed: while(rule) { char *expression = rule->name; - if ((proceed = switch_regex_perform(request.uri, expression, &re, ovector, sizeof(ovector) / sizeof(ovector[0])))) { + if ((proceed = switch_regex_perform(request->uri, expression, &re, ovector, sizeof(ovector) / sizeof(ovector[0])))) { switch_log_printf(SWITCH_CHANNEL_LOG, SWITCH_LOG_DEBUG, - "%d request [%s] matched expr [%s]\n", proceed, request.uri, expression); - request.uri = rule->value; + "%d request [%s] matched expr [%s]\n", proceed, request->uri, expression); + request->uri = rule->value; break; } @@ -1772,79 +1905,49 @@ authed: } } - switch_event_add_header_string(request.headers, SWITCH_STACK_BOTTOM, "HTTP-URI", request.uri); + switch_event_add_header_string(stream.param_event, SWITCH_STACK_BOTTOM, "HTTP-URI", request->uri); - if ((ext = strrchr(request.uri, '.'))) { + if ((ext = strrchr(request->uri, '.'))) { char path[1024]; if (!strncmp(ext, ".lua", 4)) { - switch_snprintf(path, sizeof(path), "%s%s", vhost->script_root, request.uri); + switch_snprintf(path, sizeof(path), "%s%s", vhost->script_root, request->uri); switch_api_execute("lua", path, NULL, &stream); } else { - http_static_handler(&request, vhost); + http_static_handler(request, vhost); } - } else { - http_static_handler(&request, vhost); + http_static_handler(request, vhost); } done: - keepalive = request.keepalive; - switch_http_free_request(&request); + keepalive = request->keepalive; + kws_request_free(&request); + if (stream.param_event) switch_event_destroy(&stream.param_event); if (keepalive) { - wsh_t *wsh = &jsock->ws; - - memset(&request, 0, sizeof(request)); - wsh->datalen = 0; - *wsh->buffer = '\0'; + kws_t *wsh = jsock->ws; while(jsock->profile->running) { - int pflags; - - if (wsh->ssl && SSL_pending(wsh->ssl) > 0) { - pflags = SWITCH_POLL_READ; - } else { - pflags = switch_wait_sock(jsock->client_socket, 3000, SWITCH_POLL_READ | SWITCH_POLL_ERROR | SWITCH_POLL_HUP); - } + int pflags = kws_wait_sock(wsh, 3000, KS_POLL_READ); if (jsock->drop) { die("%s Dropping Connection\n", jsock->name); } if (pflags < 0 && (errno != EINTR)) { die_errnof("%s POLL FAILED with %d", jsock->name, pflags); } if (pflags == 0) { /* keepalive socket poll timeout */ break; } - if (pflags > 0 && (pflags & SWITCH_POLL_HUP)) { log_and_exit(SWITCH_LOG_INFO, "%s POLL HANGUP DETECTED (peer closed its end of socket)\n", jsock->name); } - if (pflags > 0 && (pflags & SWITCH_POLL_ERROR)) { die("%s POLL ERROR\n", jsock->name); } - if (pflags > 0 && (pflags & SWITCH_POLL_INVALID)) { die("%s POLL INVALID SOCKET (not opened or already closed)\n", jsock->name); } - if (pflags > 0 && (pflags & SWITCH_POLL_READ)) { - ssize_t bytes; - - bytes = ws_raw_read(wsh, wsh->buffer + wsh->datalen, wsh->buflen - wsh->datalen - 1, wsh->block); - - if (bytes < 0) { - die("%s BAD READ %" SWITCH_SIZE_T_FMT "\n", jsock->name, bytes); - break; - } - - if (bytes == 0) { - bytes = ws_raw_read(wsh, wsh->buffer + wsh->datalen, wsh->buflen - wsh->datalen - 1, wsh->block); - - if (bytes < 0) { - die("%s BAD READ %" SWITCH_SIZE_T_FMT "\n", jsock->name, bytes); - break; - } - - if (bytes == 0) { // socket broken ? - break; - } - } - - wsh->datalen += bytes; - *(wsh->buffer + wsh->datalen) = '\0'; - - if (strstr(wsh->buffer, "\r\n\r\n") || strstr(wsh->buffer, "\n\n")) { + if (pflags > 0 && (pflags & KS_POLL_HUP)) { log_and_exit(SWITCH_LOG_INFO, "%s POLL HANGUP DETECTED (peer closed its end of socket)\n", jsock->name); } + if (pflags > 0 && (pflags & KS_POLL_ERROR)) { die("%s POLL ERROR\n", jsock->name); } + if (pflags > 0 && (pflags & KS_POLL_INVALID)) { die("%s POLL INVALID SOCKET (not opened or already closed)\n", jsock->name); } + if (pflags > 0 && (pflags & KS_POLL_READ)) { + if (kws_keepalive(wsh) == KS_STATUS_SUCCESS) { switch_log_printf(SWITCH_CHANNEL_LOG, SWITCH_LOG_DEBUG, "socket %s is going to handle a new request\n", jsock->name); goto new_req; + } else { + // switch_log_printf(SWITCH_CHANNEL_LOG, SWITCH_LOG_ERROR, "Socket Read Error\n"); + break; } + } else { + switch_log_printf(SWITCH_CHANNEL_LOG, SWITCH_LOG_WARNING, "unhandled flag: %d\n", pflags); } } } @@ -1852,12 +1955,12 @@ done: return; request_err: - switch_http_free_request(&request); + kws_request_free(&request); err: err = "HTTP/1.1 500 Internal Server Error\r\n" "Content-Length: 0\r\n\r\n"; - ws_raw_write(&jsock->ws, err, strlen(err)); + kws_raw_write(jsock->ws, err, strlen(err)); error: return; @@ -1865,40 +1968,78 @@ error: static void client_run(jsock_t *jsock) { - if (ws_init(&jsock->ws, jsock->client_socket, (jsock->ptype & PTYPE_CLIENT_SSL) ? jsock->profile->ssl_ctx : NULL, 0, 1, !!jsock->profile->vhosts) < 0) { - if (jsock->profile->vhosts) { - http_run(jsock); - ws_close(&jsock->ws, WS_NONE); - goto error; - } else { - log_and_exit(SWITCH_LOG_NOTICE, "%s WS SETUP FAILED\n", jsock->name); - } + int flags = KWS_BLOCK; + int idle = 0; + + if (jsock->profile->vhosts) { + flags |= KWS_STAY_OPEN; + flags |= KWS_HTTP; + } + + ks_pool_open(&jsock->kpool); + if (kws_init(&jsock->ws, jsock->client_socket, (jsock->ptype & PTYPE_CLIENT_SSL) ? jsock->profile->ssl_ctx : NULL, 0, flags, jsock->kpool) != KS_STATUS_SUCCESS) { + log_and_exit(SWITCH_LOG_NOTICE, "%s WS SETUP FAILED\n", jsock->name); + } + + if (kws_test_flag(jsock->ws, KWS_HTTP)) { + http_run(jsock); + kws_close(jsock->ws, WS_NONE); + goto end; } while(jsock->profile->running) { - int pflags; + int pflags, poll_time = 50; + time_t now; + + if (!jsock->ws) { die("%s Setup Error\n", jsock->name); } + + pflags = kws_wait_sock(jsock->ws, poll_time, KS_POLL_READ); + + if (jsock->exptime) { + now = switch_epoch_time_now(NULL); + + if (now >= jsock->exptime) { + switch_set_flag(jsock, JPFLAG_AUTH_EXPIRED); + die("%s Authentication Expired [%ld] >= [%ld]\n", jsock->uid, now, jsock->exptime); + } - if (jsock->ws.ssl && SSL_pending(jsock->ws.ssl) > 0) { - pflags = SWITCH_POLL_READ; - } else { - pflags = switch_wait_sock(jsock->client_socket, 50, SWITCH_POLL_READ | SWITCH_POLL_ERROR | SWITCH_POLL_HUP); } if (jsock->drop) { die("%s Dropping Connection\n", jsock->name); } if (pflags < 0 && (errno != EINTR)) { die_errnof("%s POLL FAILED with %d", jsock->name, pflags); } - if (pflags == 0) {/* socket poll timeout */ jsock_check_event_queue(jsock); } - if (pflags > 0 && (pflags & SWITCH_POLL_HUP)) { log_and_exit(SWITCH_LOG_INFO, "%s POLL HANGUP DETECTED (peer closed its end of socket)\n", jsock->name); } - if (pflags > 0 && (pflags & SWITCH_POLL_ERROR)) { die("%s POLL ERROR\n", jsock->name); } - if (pflags > 0 && (pflags & SWITCH_POLL_INVALID)) { die("%s POLL INVALID SOCKET (not opened or already closed)\n", jsock->name); } - if (pflags > 0 && (pflags & SWITCH_POLL_READ)) { + if (pflags == 0) {/* socket poll timeout */ jsock_check_event_queue(jsock); idle += poll_time;} else {idle = 0;} + + if (idle >= 30000) { + cJSON *params = NULL; + cJSON *msg = jrpc_new_req("verto.ping", 0, ¶ms); + + if (jsock->exptime) { + cJSON_AddItemToObject(params, "auth-expires", cJSON_CreateNumber(jsock->exptime)); + } + + cJSON_AddItemToObject(params, "serno", cJSON_CreateNumber(switch_epoch_time_now(NULL))); + jsock_queue_event(jsock, &msg, SWITCH_TRUE); + idle = 0; + } + + if ((!switch_test_flag(jsock, JPFLAG_CHECK_ATTACH) || (jsock->attach_timer > 0 && jsock->attach_timer-- == 0)) && + switch_test_flag(jsock, JPFLAG_AUTHED)) { + attach_calls(jsock); + switch_set_flag(jsock, JPFLAG_CHECK_ATTACH); + } + + if (pflags > 0 && (pflags & KS_POLL_HUP)) { log_and_exit(SWITCH_LOG_INFO, "%s POLL HANGUP DETECTED (peer closed its end of socket)\n", jsock->name); } + if (pflags > 0 && (pflags & KS_POLL_ERROR)) { die("%s POLL ERROR\n", jsock->name); } + if (pflags > 0 && (pflags & KS_POLL_INVALID)) { die("%s POLL INVALID SOCKET (not opened or already closed)\n", jsock->name); } + if (pflags > 0 && (pflags & KS_POLL_READ)) { switch_ssize_t bytes; - ws_opcode_t oc; + kws_opcode_t oc; uint8_t *data; - bytes = ws_read_frame(&jsock->ws, &oc, &data); + bytes = kws_read_frame(jsock->ws, &oc, &data); if (bytes < 0) { - if (bytes == -WS_RECV_CLOSE) { + if (bytes == -1000) { log_and_exit(SWITCH_LOG_INFO, "%s Client sent close request\n", jsock->name); } else { die("%s BAD READ %" SWITCH_SSIZE_T_FMT "\n", jsock->name, bytes); @@ -1927,7 +2068,7 @@ static void client_run(jsock_t *jsock) a = switch_time_now(); do { - bytes = ws_read_frame(&jsock->ws, &oc, &data); + bytes = kws_read_frame(jsock->ws, &oc, &data); s = (char *) data; } while (bytes && data && s[0] == '#' && s[3] == 'B'); b = switch_time_now(); @@ -1937,7 +2078,7 @@ static void client_run(jsock_t *jsock) if (s[0] != '#') goto nm; switch_snprintf(repl, sizeof(repl), "#SPU %ld", (long)((b - a) / 1000)); - ws_write_frame(&jsock->ws, WSOC_TEXT, repl, strlen(repl)); + kws_write_frame(jsock->ws, WSOC_TEXT, repl, strlen(repl)); loops = size / 1024; rem = size % 1024; switch_snprintf(repl, sizeof(repl), "#SPB "); @@ -1947,10 +2088,10 @@ static void client_run(jsock_t *jsock) int ddur = 0; a = switch_time_now(); for (i = 0; i < loops; i++) { - ws_write_frame(&jsock->ws, WSOC_TEXT, repl, 1024); + kws_write_frame(jsock->ws, WSOC_TEXT, repl, 1024); } if (rem) { - ws_write_frame(&jsock->ws, WSOC_TEXT, repl, rem); + kws_write_frame(jsock->ws, WSOC_TEXT, repl, rem); } b = switch_time_now(); ddur += (int)((b - a) / 1000); @@ -1961,7 +2102,7 @@ static void client_run(jsock_t *jsock) dur /= j+1; switch_snprintf(repl, sizeof(repl), "#SPD %d", dur); - ws_write_frame(&jsock->ws, WSOC_TEXT, repl, strlen(repl)); + kws_write_frame(jsock->ws, WSOC_TEXT, repl, strlen(repl)); } } @@ -1973,20 +2114,15 @@ static void client_run(jsock_t *jsock) if (process_input(jsock, data, bytes) != SWITCH_STATUS_SUCCESS) { die("%s Input Error\n", jsock->name); } - - if (!switch_test_flag(jsock, JPFLAG_CHECK_ATTACH) && switch_test_flag(jsock, JPFLAG_AUTHED)) { - attach_calls(jsock); - switch_set_flag(jsock, JPFLAG_CHECK_ATTACH); - } } } } error: - + end: detach_jsock(jsock); - ws_destroy(&jsock->ws); - + kws_destroy(&jsock->ws); + ks_pool_close(&jsock->kpool); return; } @@ -2031,7 +2167,7 @@ static void *SWITCH_THREAD_FUNC client_thread(switch_thread_t *thread, void *obj switch_event_destroy(&jsock->vars); switch_event_destroy(&jsock->user_vars); - if (jsock->client_socket != ws_sock_invalid) { + if (jsock->client_socket != KS_SOCK_INVALID) { close_socket(&jsock->client_socket); } @@ -2206,7 +2342,7 @@ static switch_status_t verto_connect(switch_core_session_t *session, const char switch_status_t status = SWITCH_STATUS_SUCCESS; jsock_t *jsock = NULL; verto_pvt_t *tech_pvt = switch_core_session_get_private_class(session, SWITCH_PVT_SECONDARY); - + if (!(jsock = get_jsock(tech_pvt->jsock_uuid))) { status = SWITCH_STATUS_BREAK; } else { @@ -2214,7 +2350,7 @@ static switch_status_t verto_connect(switch_core_session_t *session, const char cJSON *msg = NULL; const char *var = NULL; switch_caller_profile_t *caller_profile = switch_channel_get_caller_profile(tech_pvt->channel); - switch_event_header_t *hp; + switch_event_header_t *hi; //DUMP_EVENT(jsock->params); @@ -2224,10 +2360,12 @@ static switch_status_t verto_connect(switch_core_session_t *session, const char switch_channel_set_variable(tech_pvt->channel, "chat_proto", VERTO_CHAT_PROTO); switch_channel_set_variable(tech_pvt->channel, "verto_host", jsock->domain); - for (hp = jsock->user_vars->headers; hp; hp = hp->next) { - switch_channel_set_variable(tech_pvt->channel, hp->name, hp->value); + switch_mutex_lock(jsock->flag_mutex); + for (hi = jsock->user_vars->headers; hi; hi = hi->next) { + switch_channel_set_variable(tech_pvt->channel, hi->name, hi->value); } - + switch_mutex_unlock(jsock->flag_mutex); + if ((var = switch_event_get_header(jsock->params, "caller-id-name"))) { caller_profile->callee_id_name = switch_core_strdup(caller_profile->pool, var); } @@ -2267,6 +2405,8 @@ static switch_status_t verto_connect(switch_core_session_t *session, const char msg = jrpc_new_req(method, tech_pvt->call_id, ¶ms); + add_variables(tech_pvt, params); + if (tech_pvt->mparams->local_sdp_str) { switch_log_printf(SWITCH_CHANNEL_SESSION_LOG(session), SWITCH_LOG_DEBUG, "Local %s SDP %s:\n%s\n", method, @@ -2551,10 +2691,13 @@ static switch_status_t verto_send_media_indication(switch_core_session_t *sessio } else { cJSON *params = NULL; cJSON *msg = jrpc_new_req(method, tech_pvt->call_id, ¶ms); + if (!switch_test_flag(tech_pvt, TFLAG_SENT_MEDIA)) { cJSON_AddItemToObject(params, "sdp", cJSON_CreateString(tech_pvt->mparams->local_sdp_str)); } + add_variables(tech_pvt, params); + switch_set_flag(tech_pvt, TFLAG_SENT_MEDIA); if (jsock_queue_event(jsock, &msg, SWITCH_TRUE) != SWITCH_STATUS_SUCCESS) { @@ -2598,6 +2741,67 @@ static switch_status_t messagehook (switch_core_session_t *session, switch_core_ switch_thread_rwlock_unlock(jsock->rwlock); } + } + break; + case SWITCH_MESSAGE_INDICATE_PROMPT: + { + const char *type = NULL, *text = NULL, *regex = NULL; + cJSON *jmsg = NULL, *params = NULL; + jsock_t *jsock = NULL; + + if ((jsock = get_jsock(tech_pvt->jsock_uuid))) { + + type = msg->string_array_arg[0]; + text = msg->string_array_arg[1]; + regex = msg->string_array_arg[2]; + + if (type && (!strcasecmp(type, "dtmf") || !strcasecmp(type, "message")) && text) { + jmsg = jrpc_new_req("verto.prompt", tech_pvt->call_id, ¶ms); + + cJSON_AddItemToObject(params, "type", cJSON_CreateString(type)); + cJSON_AddItemToObject(params, "text", cJSON_CreateString(text)); + + if (regex) { + cJSON_AddItemToObject(params, "regex", cJSON_CreateString(regex)); + } + + jsock_queue_event(jsock, &jmsg, SWITCH_TRUE); + + } else { + switch_log_printf(SWITCH_CHANNEL_LOG, SWITCH_LOG_WARNING, "Error Parsing Media Params\n"); + r = SWITCH_STATUS_FALSE; + } + + + switch_thread_rwlock_unlock(jsock->rwlock); + } + } + break; + case SWITCH_MESSAGE_INDICATE_MEDIA_PARAMS: + { + const char *json_text; + cJSON *jmsg = NULL, *params = NULL, *vparams = NULL; + jsock_t *jsock = NULL; + + if ((jsock = get_jsock(tech_pvt->jsock_uuid))) { + + json_text = msg->string_arg; + + if (json_text) { + jmsg = jrpc_new_req("verto.mediaParams", tech_pvt->call_id, ¶ms); + if ((vparams = cJSON_Parse((char *)json_text))) { + cJSON_AddItemToObject(params, "mediaParams", vparams); + jsock_queue_event(jsock, &jmsg, SWITCH_TRUE); + } else { + switch_log_printf(SWITCH_CHANNEL_LOG, SWITCH_LOG_WARNING, "Error Parsing Media Params\n"); + r = SWITCH_STATUS_FALSE; + cJSON_Delete(jmsg); + } + } + + switch_thread_rwlock_unlock(jsock->rwlock); + } + } break; case SWITCH_MESSAGE_INDICATE_MEDIA_RENEG: @@ -2613,10 +2817,14 @@ static switch_status_t messagehook (switch_core_session_t *session, switch_core_ } break; case SWITCH_MESSAGE_INDICATE_ANSWER: + switch_channel_set_variable(tech_pvt->channel, SWITCH_ENDPOINT_DISPOSITION_VARIABLE, "ANSWERED"); + switch_channel_mark_pre_answered(tech_pvt->channel); r = verto_send_media_indication(session, "verto.answer"); break; case SWITCH_MESSAGE_INDICATE_PROGRESS: r = verto_send_media_indication(session, "verto.media"); + switch_channel_set_variable(tech_pvt->channel, SWITCH_ENDPOINT_DISPOSITION_VARIABLE, "EARLY MEDIA"); + switch_channel_mark_pre_answered(tech_pvt->channel); break; default: break; @@ -2636,7 +2844,7 @@ static int verto_recover_callback(switch_core_session_t *session) const char *profile_name = NULL, *jsock_uuid_str = NULL; switch_channel_t *channel = switch_core_session_get_channel(session); - if (switch_channel_test_flag(channel, CF_VIDEO_ONLY)) { + if (switch_channel_test_flag(channel, CF_NO_RECOVER)) { return 0; } @@ -2752,7 +2960,9 @@ static switch_bool_t verto__answer_func(const char *method, cJSON *params, jsock switch_log_printf(SWITCH_CHANNEL_SESSION_LOG(session), SWITCH_LOG_DEBUG, "Remote SDP %s:\n%s\n", switch_channel_get_name(tech_pvt->channel), sdp); switch_core_media_set_sdp_codec_string(session, sdp, SDP_TYPE_RESPONSE); - switch_ivr_set_user(session, jsock->uid); + if (!switch_channel_var_true(switch_core_session_get_channel(session),"verto_skip_set_user")) { + switch_ivr_set_user(session, jsock->uid); + } if (switch_core_session_get_partner(tech_pvt->session, &other_session) == SWITCH_STATUS_SUCCESS) { switch_channel_t *other_channel = switch_core_session_get_channel(other_session); @@ -3164,8 +3374,9 @@ static switch_bool_t verto__modify_func(const char *method, cJSON *params, jsock switch_core_session_t *session; cJSON *dialog = NULL; const char *call_id = NULL, *destination = NULL, *action = NULL; - int err = 0; - + int err = 0, is_reinvite = 0; + verto_pvt_t *tech_pvt = NULL; + *response = obj; if (!params) { @@ -3188,14 +3399,72 @@ static switch_bool_t verto__modify_func(const char *method, cJSON *params, jsock err = 1; goto cleanup; } + + cJSON_AddItemToObject(obj, "callID", cJSON_CreateString(call_id)); cJSON_AddItemToObject(obj, "action", cJSON_CreateString(action)); if ((session = switch_core_session_locate(call_id))) { - verto_pvt_t *tech_pvt = switch_core_session_get_private_class(session, SWITCH_PVT_SECONDARY); + tech_pvt = switch_core_session_get_private_class(session, SWITCH_PVT_SECONDARY); - if (!strcasecmp(action, "transfer")) { + if (!strcasecmp(action, "videoRefresh")) { + switch_core_media_gen_key_frame(tech_pvt->session); + switch_channel_set_flag(tech_pvt->channel, CF_VIDEO_REFRESH_REQ); + } else if (!strcasecmp(action, "updateMedia")) { + const char *sdp = NULL; + uint8_t match = 0, p = 0; + + if (!switch_channel_test_flag(tech_pvt->channel, CF_ANSWERED)) { + switch_channel_hangup(tech_pvt->channel, SWITCH_CAUSE_DESTINATION_OUT_OF_ORDER); + cJSON_AddItemToObject(obj, "message", cJSON_CreateString("Cannot update a call that has not been answered.")); + err = 1; goto rwunlock; + } + + is_reinvite = 1; + + if (!(sdp = cJSON_GetObjectCstr(params, "sdp"))) { + cJSON_AddItemToObject(obj, "message", cJSON_CreateString("SDP missing")); + err = 1; goto rwunlock; + } + + tech_pvt->r_sdp = switch_core_session_strdup(session, sdp); + + + switch_channel_set_variable(tech_pvt->channel, SWITCH_R_SDP_VARIABLE, tech_pvt->r_sdp); + switch_log_printf(SWITCH_CHANNEL_SESSION_LOG(session), SWITCH_LOG_DEBUG, "updateMedia: Remote SDP %s:\n%s\n", + switch_channel_get_name(tech_pvt->channel), tech_pvt->r_sdp); + + switch_core_media_clear_ice(tech_pvt->session); + switch_channel_set_flag(tech_pvt->channel, CF_REINVITE); + //switch_channel_set_flag(tech_pvt->channel, CF_RECOVERING); + + //switch_channel_audio_sync(tech_pvt->channel); + //switch_channel_set_flag(tech_pvt->channel, CF_VIDEO_BREAK); + //switch_core_session_kill_channel(tech_pvt->session, SWITCH_SIG_BREAK); + + if ((match = switch_core_media_negotiate_sdp(tech_pvt->session, tech_pvt->r_sdp, &p, SDP_TYPE_REQUEST))) { + switch_core_media_gen_local_sdp(session, SDP_TYPE_RESPONSE, NULL, 0, NULL, 0); + + if (switch_core_media_activate_rtp(tech_pvt->session) != SWITCH_STATUS_SUCCESS) { + switch_channel_set_variable(tech_pvt->channel, SWITCH_ENDPOINT_DISPOSITION_VARIABLE, "MEDIA ERROR"); + cJSON_AddItemToObject(obj, "message", cJSON_CreateString("MEDIA ERROR")); + err = 1; goto rwunlock; + } + + cJSON_AddItemToObject(obj, "sdp", cJSON_CreateString(tech_pvt->mparams->local_sdp_str)); + switch_log_printf(SWITCH_CHANNEL_SESSION_LOG(session), SWITCH_LOG_DEBUG, "updateMedia: Local SDP %s:\n%s\n", + switch_channel_get_name(tech_pvt->channel), tech_pvt->mparams->local_sdp_str); + switch_core_media_gen_key_frame(tech_pvt->session); + switch_channel_set_flag(tech_pvt->channel, CF_VIDEO_REFRESH_REQ); + switch_channel_set_flag(tech_pvt->channel, CF_REATTACHED); + } else { + switch_channel_set_variable(tech_pvt->channel, SWITCH_ENDPOINT_DISPOSITION_VARIABLE, "CODEC NEGOTIATION ERROR"); + cJSON_AddItemToObject(obj, "message", cJSON_CreateString("CODEC NEGOTIATION ERROR")); + err = 1; goto rwunlock; + } + + } else if (!strcasecmp(action, "transfer")) { switch_core_session_t *other_session = NULL; if (!(destination = cJSON_GetObjectCstr(params, "destination"))) { @@ -3253,6 +3522,15 @@ static switch_bool_t verto__modify_func(const char *method, cJSON *params, jsock cleanup: + if (tech_pvt && is_reinvite) { + switch_channel_clear_flag(tech_pvt->channel, CF_REINVITE); + //switch_channel_clear_flag(tech_pvt->channel, CF_RECOVERING); + switch_clear_flag(tech_pvt, TFLAG_ATTACH_REQ); + //if (switch_channel_test_flag(tech_pvt->channel, CF_CONFERENCE)) { + // switch_channel_set_flag(tech_pvt->channel, CF_CONFERENCE_ADV); + //} + } + if (!err) return SWITCH_TRUE; @@ -3324,11 +3602,16 @@ static switch_bool_t verto__attach_func(const char *method, cJSON *params, jsock //switch_core_session_kill_channel(tech_pvt->session, SWITCH_SIG_BREAK); if ((match = switch_core_media_negotiate_sdp(tech_pvt->session, tech_pvt->r_sdp, &p, SDP_TYPE_RESPONSE))) { + //switch_core_media_gen_local_sdp(session, SDP_TYPE_RESPONSE, NULL, 0, NULL, 0); + if (switch_core_media_activate_rtp(tech_pvt->session) != SWITCH_STATUS_SUCCESS) { switch_channel_set_variable(tech_pvt->channel, SWITCH_ENDPOINT_DISPOSITION_VARIABLE, "MEDIA ERROR"); cJSON_AddItemToObject(obj, "message", cJSON_CreateString("MEDIA ERROR")); err = 1; goto cleanup; } + + //cJSON_AddItemToObject(obj, "sdp", cJSON_CreateString(tech_pvt->mparams->local_sdp_str)); + } else { switch_channel_set_variable(tech_pvt->channel, SWITCH_ENDPOINT_DISPOSITION_VARIABLE, "CODEC NEGOTIATION ERROR"); cJSON_AddItemToObject(obj, "message", cJSON_CreateString("CODEC NEGOTIATION ERROR")); @@ -3339,41 +3622,85 @@ static switch_bool_t verto__attach_func(const char *method, cJSON *params, jsock if (tech_pvt) { switch_channel_clear_flag(tech_pvt->channel, CF_REINVITE); - switch_channel_clear_flag(tech_pvt->channel, CF_RECOVERING); + //switch_channel_clear_flag(tech_pvt->channel, CF_RECOVERING); switch_clear_flag(tech_pvt, TFLAG_ATTACH_REQ); if (switch_channel_test_flag(tech_pvt->channel, CF_CONFERENCE)) { switch_channel_set_flag(tech_pvt->channel, CF_CONFERENCE_ADV); } } + if (tech_pvt) { + if (err) { + if (tech_pvt->channel) { + switch_channel_hangup(tech_pvt->channel, SWITCH_CAUSE_BEARERCAPABILITY_NOTAVAIL); + } + } else { + switch_core_media_gen_key_frame(tech_pvt->session); + switch_channel_set_flag(tech_pvt->channel, CF_VIDEO_REFRESH_REQ); + switch_channel_set_flag(tech_pvt->channel, CF_REATTACHED); + } + } + if (session) { switch_core_session_rwunlock(session); } if (!err) { + const char *cid_name, *cid_num; + switch_core_session_message_t msg = { 0 }; + + cid_name = switch_channel_get_variable(tech_pvt->channel, "last_sent_display_name"); + cid_num = switch_channel_get_variable(tech_pvt->channel, "last_sent_display_number"); + + msg.from = __FILE__; + msg.string_array_arg[0] = cid_name; + msg.string_array_arg[1] = cid_num; + + msg.message_id = SWITCH_MESSAGE_INDICATE_DISPLAY; + switch_core_session_receive_message(session, &msg); + return SWITCH_TRUE; } - if (tech_pvt && tech_pvt->channel) { - switch_channel_hangup(tech_pvt->channel, SWITCH_CAUSE_BEARERCAPABILITY_NOTAVAIL); - } - - cJSON_AddItemToObject(obj, "code", cJSON_CreateNumber(CODE_SESSION_ERROR)); return SWITCH_FALSE; } + static void parse_user_vars(cJSON *obj, switch_core_session_t *session) { - cJSON *json_ptr; - + cJSON *json_ptr, *var; + switch_channel_t *channel; + switch_assert(obj); switch_assert(session); + channel = switch_core_session_get_channel(session); + + + if ((json_ptr = cJSON_GetObjectItem(obj, "audio"))) { + if ((var = cJSON_GetObjectItem(json_ptr, "echoCancellation")) && var->type == cJSON_True) { + switch_channel_set_variable(channel, "verto_echoCancellation", "true"); + } else { + switch_channel_set_variable(channel, "verto_echoCancellation", "false"); + } + + if ((var = cJSON_GetObjectItem(json_ptr, "noiseSuppression")) && var->type == cJSON_True) { + switch_channel_set_variable(channel, "verto_noiseSuppression", "true"); + } else { + switch_channel_set_variable(channel, "verto_noiseSuppression", "false"); + } + + if ((var = cJSON_GetObjectItem(json_ptr, "autoGainControl")) && var->type == cJSON_True) { + switch_channel_set_variable(channel, "verto_autoGainControl", "true"); + } else { + switch_channel_set_variable(channel, "verto_autoGainControl", "false"); + } + } + if ((json_ptr = cJSON_GetObjectItem(obj, "userVariables"))) { cJSON * i; - switch_channel_t *channel = switch_core_session_get_channel(session); for(i = json_ptr->child; i; i = i->next) { char *varname = switch_core_session_sprintf(session, "verto_dvar_%s", i->string); @@ -3389,10 +3716,22 @@ static void parse_user_vars(cJSON *obj, switch_core_session_t *session) } } +static switch_bool_t verto__ping_func(const char *method, cJSON *params, jsock_t *jsock, cJSON **response) +{ + *response = cJSON_CreateObject(); + + if (jsock->exptime) { + cJSON_AddItemToObject(*response, "auth-expires", cJSON_CreateNumber(jsock->exptime)); + } + + cJSON_AddItemToObject(*response, "message", cJSON_CreateString("PONG")); + return SWITCH_TRUE; +} + static switch_bool_t verto__info_func(const char *method, cJSON *params, jsock_t *jsock, cJSON **response) { - cJSON *msg = NULL, *dialog = NULL, *txt = NULL; - const char *call_id = NULL, *dtmf = NULL; + cJSON *msg = NULL, *dialog = NULL, *txt = NULL, *jevent = NULL; + const char *call_id = NULL, *dtmf = NULL, *type = NULL; switch_bool_t r = SWITCH_TRUE; char *proto = VERTO_CHAT_PROTO; char *pproto = NULL; @@ -3405,21 +3744,54 @@ static switch_bool_t verto__info_func(const char *method, cJSON *params, jsock_t err = 1; goto cleanup; } + type = cJSON_GetObjectCstr(params, "type"); + if ((dialog = cJSON_GetObjectItem(params, "dialogParams")) && (call_id = cJSON_GetObjectCstr(dialog, "callID"))) { switch_core_session_t *session = NULL; - + switch_channel_t *channel = NULL; + if ((session = switch_core_session_locate(call_id))) { + verto_pvt_t *tech_pvt = switch_core_session_get_private_class(session, SWITCH_PVT_SECONDARY); + if (!tech_pvt) { + cJSON_AddItemToObject(*response, "message", cJSON_CreateString("Invalid channel")); + switch_core_session_rwunlock(session); + err = 1; goto cleanup; + } + + channel = switch_core_session_get_channel(session); parse_user_vars(dialog, session); - if ((dtmf = cJSON_GetObjectCstr(params, "dtmf"))) { - verto_pvt_t *tech_pvt = switch_core_session_get_private_class(session, SWITCH_PVT_SECONDARY); - char *send; + if (type && !strcasecmp(type, "mediaSettings")) { + switch_channel_set_flag(channel, CF_DEVICES_CHANGED); + } + + if ((jevent = cJSON_GetObjectItem(params, "command"))) { + switch_event_t *event = NULL; - if (!tech_pvt) { - cJSON_AddItemToObject(*response, "message", cJSON_CreateString("Invalid channel")); - err = 1; goto cleanup; + if (switch_event_create(&event, SWITCH_EVENT_COMMAND) == SWITCH_STATUS_SUCCESS) { + char *json_text; + + json_text = cJSON_PrintUnformatted(jevent); + switch_assert(json_text); + + switch_event_add_header_string(event, SWITCH_STACK_BOTTOM, "content-type", "text/json"); + switch_event_add_header_string(event, SWITCH_STACK_BOTTOM, "content-source", "verto"); + switch_event_add_body(event, "%s", json_text); + + switch_safe_free(json_text); + + if (switch_core_session_queue_event(session, &event) != SWITCH_STATUS_SUCCESS) { + switch_event_destroy(&event); + cJSON_AddItemToObject(*response, "message", cJSON_CreateString("Unexpected Error")); + switch_core_session_rwunlock(session); + err = 1; goto cleanup; + } } + } + + if ((dtmf = cJSON_GetObjectCstr(params, "dtmf"))) { + char *send; send = switch_mprintf("~%s", dtmf); @@ -3573,7 +3945,7 @@ static switch_bool_t verto__info_func(const char *method, cJSON *params, jsock_t static switch_bool_t verto__invite_func(const char *method, cJSON *params, jsock_t *jsock, cJSON **response) { - cJSON *obj = cJSON_CreateObject(), *screenShare = NULL, *dedEnc = NULL, *mirrorInput, *bandwidth = NULL, *canvas = NULL; + cJSON *obj = cJSON_CreateObject(), *vobj = NULL, *dedEnc = NULL, *mirrorInput, *bandwidth = NULL, *canvas = NULL; switch_core_session_t *session = NULL; switch_channel_t *channel; switch_event_t *var_event; @@ -3655,9 +4027,16 @@ static switch_bool_t verto__invite_func(const char *method, cJSON *params, jsock err = 1; goto cleanup; } - if ((screenShare = cJSON_GetObjectItem(dialog, "screenShare")) && screenShare->type == cJSON_True) { + if ((vobj = cJSON_GetObjectItem(dialog, "screenShare")) && vobj->type == cJSON_True) { switch_channel_set_variable(channel, "video_screen_share", "true"); - switch_channel_set_flag(channel, CF_VIDEO_ONLY); + } + + if ((vobj = cJSON_GetObjectItem(dialog, "secondSource")) && vobj->type == cJSON_True) { + switch_channel_set_variable(channel, "video_second_source", "true"); + } + + if ((vobj = cJSON_GetObjectItem(dialog, "recoverCall")) && vobj->type == cJSON_False) { + switch_channel_set_flag(channel, CF_NO_RECOVER); } if ((dedEnc = cJSON_GetObjectItem(dialog, "dedEnc")) && dedEnc->type == cJSON_True) { @@ -3749,7 +4128,9 @@ static switch_bool_t verto__invite_func(const char *method, cJSON *params, jsock caller_id_name = var; } } else if (caller_id_name) { - switch_event_add_header_string(jsock->params, SWITCH_STACK_BOTTOM, "caller-id-name", caller_id_name); + if (!switch_event_get_header(jsock->params, "caller-id-name")) { + switch_event_add_header_string(jsock->params, SWITCH_STACK_BOTTOM, "caller-id-name", caller_id_name); + } } if (zstr(caller_id_number)) { @@ -3758,10 +4139,12 @@ static switch_bool_t verto__invite_func(const char *method, cJSON *params, jsock } } + switch_mutex_lock(jsock->flag_mutex); if (!(context = switch_event_get_header(jsock->vars, "user_context"))) { context = switch_either(jsock->context, jsock->profile->context); } - + switch_mutex_unlock(jsock->flag_mutex); + if ((caller_profile = switch_caller_profile_new(switch_core_session_get_pool(session), jsock->uid, switch_either(jsock->dialplan, jsock->profile->dialplan), @@ -3779,12 +4162,15 @@ static switch_bool_t verto__invite_func(const char *method, cJSON *params, jsock } - switch_ivr_set_user(session, jsock->uid); + if (!switch_channel_var_true(channel,"verto_skip_set_user")) { + switch_ivr_set_user(session, jsock->uid); + } + switch_mutex_lock(jsock->flag_mutex); for (hp = jsock->user_vars->headers; hp; hp = hp->next) { switch_channel_set_variable(channel, hp->name, hp->value); } - + switch_mutex_unlock(jsock->flag_mutex); switch_channel_set_profile_var(channel, "callee_id_name", remote_caller_id_name); switch_channel_set_profile_var(channel, "callee_id_number", remote_caller_id_number); @@ -4032,6 +4418,7 @@ static switch_bool_t verto__broadcast_func(const char *method, cJSON *params, js cJSON_AddItemToObject(params, "userid", cJSON_CreateString(jsock->uid)); + cJSON_AddItemToObject(params, "sessid", cJSON_CreateString(jsock->uuid_str)); display = switch_event_get_header(jsock->params, "caller-id-name"); if (display) { @@ -4043,12 +4430,12 @@ static switch_bool_t verto__broadcast_func(const char *method, cJSON *params, js broadcast = cJSON_GetObjectItem(params, "localBroadcast"); if (broadcast && broadcast->type == cJSON_True) { - write_event(event_channel, NULL, jevent); + write_event(event_channel, NULL, NULL, jevent); } else { switch_event_channel_broadcast(event_channel, &jevent, modname, verto_globals.event_channel_id); } - if (jsock->profile->mcast_pub.sock != ws_sock_invalid) { + if (jsock->profile->mcast_pub.sock != KS_SOCK_INVALID) { if ((json_text = cJSON_PrintUnformatted(params))) { if (mcast_socket_send(&jsock->profile->mcast_pub, json_text, strlen(json_text) + 1) <= 0) { @@ -4059,7 +4446,7 @@ static switch_bool_t verto__broadcast_func(const char *method, cJSON *params, js //r = SWITCH_TRUE; //cJSON_AddItemToObject(*response, "message", cJSON_CreateString("MCAST Data Sent")); if (verto_globals.debug > 0) { - switch_log_printf(SWITCH_CHANNEL_LOG, SWITCH_LOG_DEBUG, "MCAST Data Sent: %s\n",json_text); + switch_log_printf(SWITCH_CHANNEL_LOG, verto_globals.debug_level, "MCAST Data Sent: %s\n",json_text); } } free(json_text); @@ -4076,9 +4463,30 @@ static switch_bool_t verto__broadcast_func(const char *method, cJSON *params, js static switch_bool_t login_func(const char *method, cJSON *params, jsock_t *jsock, cJSON **response) { + const char *var; *response = cJSON_CreateObject(); cJSON_AddItemToObject(*response, "message", cJSON_CreateString("logged in")); + if (jsock->exptime) { + cJSON_AddItemToObject(*response, "auth-expires", cJSON_CreateNumber(jsock->exptime)); + } + + switch_mutex_lock(jsock->flag_mutex); + if ((var = switch_event_get_header(jsock->vars, "moderator")) && switch_true(var)) { + cJSON_AddItemToObject(*response, "moderator", cJSON_CreateTrue()); + switch_event_add_header_string(jsock->vars, SWITCH_STACK_BOTTOM, "conf_mvar_moderator", "true"); + } + + if ((var = switch_event_get_header(jsock->vars, "stereo_audio")) && switch_true(var)) { + cJSON_AddItemToObject(*response, "stereoAudio", cJSON_CreateTrue()); + } + + if ((var = switch_event_get_header(jsock->vars, "superuser")) && switch_true(var)) { + switch_event_add_header_string(jsock->vars, SWITCH_STACK_BOTTOM, "conf_mvar_superuser", "true"); + cJSON_AddItemToObject(*response, "superuser", cJSON_CreateTrue()); + } + switch_mutex_unlock(jsock->flag_mutex); + login_fire_custom_event(jsock, params, 1, "Logged in"); return SWITCH_TRUE; @@ -4101,6 +4509,10 @@ static switch_bool_t echo_func(const char *method, cJSON *params, jsock_t *jsock static switch_bool_t jsapi_func(const char *method, cJSON *params, jsock_t *jsock, cJSON **response) { + switch_event_header_t *hi = NULL; + cJSON *obj; + const char *var; + if (jsock->allowed_jsapi) { const char *function; @@ -4126,6 +4538,32 @@ static switch_bool_t jsapi_func(const char *method, cJSON *params, jsock_t *jsoc } } + obj = cJSON_CreateObject(); + cJSON_AddItemToObject(obj, "verto_id", cJSON_CreateString((char *)jsock->id)); + cJSON_AddItemToObject(obj, "verto_domain", cJSON_CreateString((char *)jsock->domain)); + cJSON_AddItemToObject(obj, "verto_user", cJSON_CreateString((char *)jsock->uid)); + cJSON_AddItemToObject(obj, "presence_id", cJSON_CreateString((char *)jsock->uid)); + cJSON_AddItemToObject(obj, "verto_client_address", cJSON_CreateString((char *)jsock->name)); + cJSON_AddItemToObject(obj, "chat_proto", cJSON_CreateString((char *)VERTO_CHAT_PROTO)); + cJSON_AddItemToObject(obj, "verto_host", cJSON_CreateString((char *)jsock->domain)); + + switch_mutex_lock(jsock->flag_mutex); + for (hi = jsock->user_vars->headers; hi; hi = hi->next) { + cJSON_AddItemToObject(obj, hi->name, cJSON_CreateString((char *)hi->value)); + } + switch_mutex_unlock(jsock->flag_mutex); + + if ((var = switch_event_get_header(jsock->params, "caller-id-name"))) { + cJSON_AddItemToObject(obj, "caller-id-name", cJSON_CreateString((char *)var)); + } + + if ((var = switch_event_get_header(jsock->params, "caller-id-number"))) { + cJSON_AddItemToObject(obj, "caller-id-number", cJSON_CreateString((char *)var)); + } + + cJSON_AddItemToObject(params, "sockData", obj); + + switch_json_api_execute(params, NULL, response); return *response ? SWITCH_TRUE : SWITCH_FALSE; @@ -4186,6 +4624,7 @@ static void jrpc_init(void) jrpc_add_func("login", login_func); jrpc_add_func("verto.invite", verto__invite_func); + jrpc_add_func("verto.ping", verto__ping_func); jrpc_add_func("verto.info", verto__info_func); jrpc_add_func("verto.attach", verto__attach_func); jrpc_add_func("verto.bye", verto__bye_func); @@ -4200,7 +4639,7 @@ static void jrpc_init(void) -static int start_jsock(verto_profile_t *profile, ws_socket_t sock, int family) +static int start_jsock(verto_profile_t *profile, ks_socket_t sock, int family) { jsock_t *jsock = NULL; int flag = 1; @@ -4303,6 +4742,7 @@ static int start_jsock(verto_profile_t *profile, ws_socket_t sock, int family) switch_mutex_init(&jsock->write_mutex, SWITCH_MUTEX_NESTED, jsock->pool); switch_mutex_init(&jsock->filter_mutex, SWITCH_MUTEX_NESTED, jsock->pool); + switch_mutex_init(&jsock->flag_mutex, SWITCH_MUTEX_NESTED, jsock->pool); switch_queue_create(&jsock->event_queue, MAX_QUEUE_LEN, jsock->pool); switch_thread_rwlock_create(&jsock->rwlock, jsock->pool); switch_thread_pool_launch_thread(&td); @@ -4312,7 +4752,7 @@ static int start_jsock(verto_profile_t *profile, ws_socket_t sock, int family) error: if (jsock) { - if (jsock->client_socket != ws_sock_invalid) { + if (jsock->client_socket != KS_SOCK_INVALID) { close_socket(&jsock->client_socket); } @@ -4322,9 +4762,9 @@ static int start_jsock(verto_profile_t *profile, ws_socket_t sock, int family) return -1; } -static ws_socket_t prepare_socket(ips_t *ips) +static ks_socket_t prepare_socket(ips_t *ips) { - ws_socket_t sock = ws_sock_invalid; + ks_socket_t sock = KS_SOCK_INVALID; #ifndef WIN32 int reuse_addr = 1; #else @@ -4378,14 +4818,14 @@ static ws_socket_t prepare_socket(ips_t *ips) close_file(&sock); - return ws_sock_invalid; + return KS_SOCK_INVALID; } static void handle_mcast_sub(verto_profile_t *profile) { int bytes; - if (profile->mcast_sub.sock == ws_sock_invalid) { + if (profile->mcast_sub.sock == KS_SOCK_INVALID) { return; } @@ -4523,7 +4963,7 @@ static void runtime(verto_profile_t *profile) for (i = 0; i < profile->i; i++) { //if ((profile->server_socket[i] = prepare_socket(profile->ip[i].local_ip_addr, profile->ip[i].local_port)) < 0) { - if ((profile->server_socket[i] = prepare_socket(&profile->ip[i])) != ws_sock_invalid) { + if ((profile->server_socket[i] = prepare_socket(&profile->ip[i])) != KS_SOCK_INVALID) { listeners++; } } @@ -4560,11 +5000,11 @@ static void runtime(verto_profile_t *profile) error: - if (profile->mcast_sub.sock != ws_sock_invalid) { + if (profile->mcast_sub.sock != KS_SOCK_INVALID) { mcast_socket_close(&profile->mcast_sub); } - if (profile->mcast_pub.sock != ws_sock_invalid) { + if (profile->mcast_pub.sock != KS_SOCK_INVALID) { mcast_socket_close(&profile->mcast_pub); } @@ -4748,9 +5188,9 @@ static switch_status_t parse_config(const char *cf) profile->local_network = "localnet.auto"; - profile->mcast_sub.sock = ws_sock_invalid; - profile->mcast_pub.sock = ws_sock_invalid; - + profile->mcast_sub.sock = KS_SOCK_INVALID; + profile->mcast_pub.sock = KS_SOCK_INVALID; + profile->chop_domain = SWITCH_TRUE; for (param = switch_xml_child(xprofile, "param"); param; param = param->next) { char *var = NULL; @@ -4792,8 +5232,12 @@ static switch_status_t parse_config(const char *cf) profile->blind_reg = switch_true(val); } else if (!strcasecmp(var, "userauth") && !zstr(val)) { profile->userauth = switch_core_strdup(profile->pool, val); + } else if (!strcasecmp(var, "chop-domain") && !zstr(val)) { + profile->chop_domain = switch_true(val); } else if (!strcasecmp(var, "root-password") && !zstr(val)) { profile->root_passwd = switch_core_strdup(profile->pool, val); + } else if (!strcasecmp(var, "send-auth-password") && !zstr(val)) { + profile->send_passwd = switch_true(val); } else if (!strcasecmp(var, "context") && !zstr(val)) { profile->context = switch_core_strdup(profile->pool, val); } else if (!strcasecmp(var, "dialplan") && !zstr(val)) { @@ -4860,7 +5304,7 @@ static switch_status_t parse_config(const char *cf) } if (zstr(profile->jb_msec)) { - profile->jb_msec = "1p:50p"; + profile->jb_msec = "1p:20p"; } if (zstr(profile->timer_name)) { @@ -4989,6 +5433,8 @@ static switch_status_t parse_config(const char *cf) } } else if (!strcasecmp(var, "enable-presence") && val) { verto_globals.enable_presence = switch_true(val); + } else if (!strcasecmp(var, "send-auth-password") && !zstr(val)) { + verto_globals.send_passwd = switch_true(val); } else if (!strcasecmp(var, "enable-fs-events") && val) { verto_globals.enable_fs_events = switch_true(val); } else if (!strcasecmp(var, "detach-timeout-sec") && val) { @@ -4996,6 +5442,10 @@ static switch_status_t parse_config(const char *cf) if (tmp > 0) { verto_globals.detach_timeout = tmp; } + } else if (!strcasecmp(var, "kslog")) { + if (val) { + verto_globals.kslog_on = switch_true(val); + } } } } @@ -5062,7 +5512,7 @@ static switch_status_t cmd_status(char **argv, int argc, switch_stream_handle_t for (i = 0; i < profile->i; i++) { char *tmpurl = switch_mprintf(strchr(profile->ip[i].local_ip, ':') ? "%s:[%s]:%d" : "%s:%s:%d", (profile->ip[i].secure == 1) ? "wss" : "ws", profile->ip[i].local_ip, profile->ip[i].local_port); - stream->write_function(stream, "%25s\t%s\t %40s\t%s\n", profile->name, "profile", tmpurl, (profile->server_socket[i] != ws_sock_invalid) ? "RUNNING" : "DOWN"); + stream->write_function(stream, "%25s\t%s\t %40s\t%s\n", profile->name, "profile", tmpurl, (profile->server_socket[i] != KS_SOCK_INVALID) ? "RUNNING" : "DOWN"); switch_safe_free(tmpurl); } cp++; @@ -5090,6 +5540,38 @@ static switch_status_t cmd_status(char **argv, int argc, switch_stream_handle_t return SWITCH_STATUS_SUCCESS; } +static switch_status_t cmd_announce(char **argv, int argc, switch_stream_handle_t *stream) +{ + verto_profile_t *profile = NULL; + jsock_t *jsock; + + switch_mutex_lock(verto_globals.mutex); + for(profile = verto_globals.profile_head; profile; profile = profile->next) { + + switch_mutex_lock(profile->mutex); + for (jsock = profile->jsock_head; jsock; jsock = jsock->next) { + cJSON *params = NULL; + cJSON *array, *msg = jrpc_new_req("verto.announce", 0, ¶ms); + int i; + + array = cJSON_CreateArray(); + + for (i = 0; i < argc; i++) { + cJSON_AddItemToArray(array, cJSON_CreateString(argv[i])); + } + + cJSON_AddItemToObject(params, "msg", array); + jsock_queue_event(jsock, &msg, SWITCH_TRUE); + } + switch_mutex_unlock(profile->mutex); + } + switch_mutex_unlock(verto_globals.mutex); + + stream->write_function(stream, "+OK\n"); + + return SWITCH_STATUS_SUCCESS; +} + static switch_status_t cmd_xml_status(char **argv, int argc, switch_stream_handle_t *stream) { verto_profile_t *profile = NULL; @@ -5126,6 +5608,81 @@ static switch_status_t cmd_xml_status(char **argv, int argc, switch_stream_handl return SWITCH_STATUS_SUCCESS; } +static cJSON *json_status() +{ + cJSON *obj, *profiles, *jprofile, *users, *user; + verto_profile_t *profile = NULL; + jsock_t *jsock; + int i; + + obj = cJSON_CreateObject(); + profiles = cJSON_CreateArray(); + + cJSON_AddItemToObject(obj, "profiles", profiles); + + switch_mutex_lock(verto_globals.mutex); + for(profile = verto_globals.profile_head; profile; profile = profile->next) { + for (i = 0; i < profile->i; i++) { + char *tmpurl = switch_mprintf(strchr(profile->ip[i].local_ip, ':') ? "%s:[%s]:%d" : "%s:%s:%d", + (profile->ip[i].secure == 1) ? "wss" : "ws", profile->ip[i].local_ip, profile->ip[i].local_port); + jprofile = cJSON_CreateObject(); + + cJSON_AddItemToObject(jprofile, "name", cJSON_CreateString(profile->name)); + cJSON_AddItemToObject(jprofile, "id", cJSON_CreateString(tmpurl)); + cJSON_AddItemToObject(jprofile, "type", cJSON_CreateString(profile->ip[i].secure == 1 ? "SECURE" : "BASIC")); + cJSON_AddItemToObject(jprofile, "state", cJSON_CreateString((profile->running) ? "RUNNING" : "DOWN")); + cJSON_AddItemToArray(profiles, jprofile); + switch_safe_free(tmpurl); + + users = cJSON_CreateArray(); + cJSON_AddItemToObject(jprofile, "users", users); + + switch_mutex_lock(profile->mutex); + for(jsock = profile->jsock_head; jsock; jsock = jsock->next) { + char *tmpname = switch_mprintf("%s@%s", jsock->id, jsock->domain); + + if (!!profile->ip[i].secure != !!(jsock->ptype & PTYPE_CLIENT_SSL)) { + continue; + } + + user = cJSON_CreateObject(); + cJSON_AddItemToObject(user, "user", cJSON_CreateString(jsock->id)); + cJSON_AddItemToObject(user, "domain", cJSON_CreateString(jsock->domain)); + cJSON_AddItemToObject(user, "entity", cJSON_CreateString(tmpname)); + cJSON_AddItemToObject(user, "type", cJSON_CreateString((jsock->ptype & PTYPE_CLIENT_SSL) ? "WSS": "WS")); + + cJSON_AddItemToObject(user, "remoteHost", cJSON_CreateString(jsock->name)); + cJSON_AddItemToObject(user, "state", cJSON_CreateString((!zstr(jsock->uid)) ? "CONN_REG" : "CONN_NO_REG")); + cJSON_AddItemToArray(users, user); + switch_safe_free(tmpname); + } + switch_mutex_unlock(profile->mutex); + } + + + } + switch_mutex_unlock(verto_globals.mutex); + + return obj; +} + +static switch_status_t cmd_json_status(char **argv, int argc, switch_stream_handle_t *stream) +{ + cJSON *record; + char *json; + + record = json_status(); + json = cJSON_Print(record); + //json = cJSON_PrintUnformatted(record); + + stream->write_function(stream, "%s\n", json); + + switch_safe_free(json); + + + return SWITCH_STATUS_SUCCESS; +} + SWITCH_STANDARD_API(verto_function) { char *argv[1024] = { 0 }; @@ -5136,8 +5693,11 @@ SWITCH_STANDARD_API(verto_function) int lead = 1; static const char usage_string[] = "USAGE:\n" "--------------------------------------------------------------------------------\n" - "verto [status|xmlstatus]\n" + "verto [status|xmlstatus|jsonstatus]\n" "verto help\n" + "verto debug [0-10]\n" + "verto perm \n" + "verto noperm \n" "--------------------------------------------------------------------------------\n"; if (zstr(cmd)) { @@ -5158,10 +5718,48 @@ SWITCH_STANDARD_API(verto_function) if (!strcasecmp(argv[0], "help")) { stream->write_function(stream, "%s", usage_string); goto done; + } else if (!strcasecmp(argv[0], "perm")) { + status = add_perm(argv[1], argv[2], argv[3], SWITCH_TRUE); + if (status == SWITCH_STATUS_SUCCESS) { + stream->write_function(stream, "+OK"); + } else { + stream->write_function(stream, "-ERR"); + } + status = SWITCH_STATUS_SUCCESS; + goto done; + } else if (!strcasecmp(argv[0], "noperm")) { + status = add_perm(argv[1], argv[2], argv[3], SWITCH_FALSE); + if (status == SWITCH_STATUS_SUCCESS) { + stream->write_function(stream, "+OK"); + } else { + stream->write_function(stream, "-ERR"); + } + status = SWITCH_STATUS_SUCCESS; + goto done; + } else if (!strcasecmp(argv[0], "announce")) { + func = cmd_announce; } else if (!strcasecmp(argv[0], "status")) { func = cmd_status; } else if (!strcasecmp(argv[0], "xmlstatus")) { func = cmd_xml_status; + } else if (!strcasecmp(argv[0], "jsonstatus")) { + func = cmd_json_status; + } else if (!strcasecmp(argv[0], "debug")) { + if (argv[1]) { + int tmp = atoi(argv[1]); + + if (tmp >= 0 && tmp <= 10) { + verto_globals.debug = tmp; + } + } + stream->write_function(stream, "Debug Level: %d\n", verto_globals.debug); + goto done; + } else if (!strcasecmp(argv[0], "debug-level")) { + if (argv[1]) { + verto_globals.debug_level = switch_log_str2level(argv[1]); + } + stream->write_function(stream, "Debug Level: %s\n", switch_log_level2str(verto_globals.debug_level)); + goto done; } if (func) { @@ -5496,7 +6094,7 @@ static switch_call_cause_t verto_outgoing_channel(switch_core_session_t *session free(dial_str); } - return cause; + goto end; } else { const char *dialed_user = switch_event_get_header(var_event, "dialed_user"); const char *dialed_domain = switch_event_get_header(var_event, "dialed_domain"); @@ -5576,8 +6174,8 @@ void verto_broadcast(const char *event_channel, cJSON *json, const char *key, sw { if (verto_globals.debug > 9) { char *json_text; - if ((json_text = cJSON_Print(json))) { - switch_log_printf(SWITCH_CHANNEL_LOG, SWITCH_LOG_DEBUG, "EVENT BROADCAST %s %s\n", event_channel, json_text); + if ((json_text = cJSON_PrintUnformatted(json))) { + switch_log_printf(SWITCH_CHANNEL_LOG, verto_globals.debug_level, "EVENT BROADCAST %s %s\n", event_channel, json_text); free(json_text); } } @@ -6121,6 +6719,25 @@ static void event_handler(switch_event_t *event) } +static void mod_verto_ks_logger(const char *file, const char *func, int line, int level, const char *fmt, ...) +{ + char fmt_buf[32768]; + va_list ap; + size_t len; + va_start(ap, fmt); + + len = snprintf(fmt_buf, sizeof(fmt_buf), "%s\n", fmt); // add return that is missing + + if (level == SWITCH_LOG_DEBUG) level = SWITCH_LOG_DEBUG1; + + if (len < sizeof(fmt_buf)) { + switch_log_vprintf(SWITCH_CHANNEL_ID_LOG, file, func, line, NULL, level, fmt_buf, ap); + } else { + switch_log_vprintf(SWITCH_CHANNEL_ID_LOG, file, func, line, NULL, level, fmt, ap); + } + va_end(ap); +} + /* Macro expands to: switch_status_t mod_verto_load(switch_loadable_module_interface_t **module_interface, switch_memory_pool_t *pool) */ SWITCH_MODULE_LOAD_FUNCTION(mod_verto_load) { @@ -6131,6 +6748,8 @@ SWITCH_MODULE_LOAD_FUNCTION(mod_verto_load) switch_cache_db_handle_t *dbh; //switch_application_interface_t *app_interface = NULL; + ks_ssl_init_skip(KS_TRUE); + ks_init(); if (switch_event_reserve_subclass(MY_EVENT_LOGIN) != SWITCH_STATUS_SUCCESS) { switch_log_printf(SWITCH_CHANNEL_LOG, SWITCH_LOG_ERROR, "Couldn't register subclass %s!\n", MY_EVENT_LOGIN); @@ -6154,7 +6773,8 @@ SWITCH_MODULE_LOAD_FUNCTION(mod_verto_load) #endif verto_globals.enable_presence = SWITCH_TRUE; verto_globals.enable_fs_events = SWITCH_FALSE; - + verto_globals.debug_level = SWITCH_LOG_INFO; + switch_mutex_init(&verto_globals.mutex, SWITCH_MUTEX_NESTED, verto_globals.pool); switch_mutex_init(&verto_globals.method_mutex, SWITCH_MUTEX_NESTED, verto_globals.pool); @@ -6194,6 +6814,11 @@ SWITCH_MODULE_LOAD_FUNCTION(mod_verto_load) if (r) return SWITCH_STATUS_TERM; + if (verto_globals.kslog_on == SWITCH_TRUE) { + ks_global_set_logger(mod_verto_ks_logger); + ks_log(KS_LOG_INFO, "ks log registered in mod_verto\n"); + } + jrpc_init(); /* connect my internal structure to the blank pointer passed to me */ @@ -6202,6 +6827,10 @@ SWITCH_MODULE_LOAD_FUNCTION(mod_verto_load) SWITCH_ADD_API(api_interface, "verto", "Verto API", verto_function, "syntax"); SWITCH_ADD_API(api_interface, "verto_contact", "Generate a verto endpoint dialstring", verto_contact_function, "user@domain"); switch_console_set_complete("add verto help"); + switch_console_set_complete("add verto debug"); + switch_console_set_complete("add verto perm"); + switch_console_set_complete("add verto noperm"); + switch_console_set_complete("add verto debug-level"); switch_console_set_complete("add verto status"); switch_console_set_complete("add verto xmlstatus"); @@ -6258,6 +6887,9 @@ SWITCH_MODULE_SHUTDOWN_FUNCTION(mod_verto_shutdown) switch_core_hash_destroy(&verto_globals.event_channel_hash); switch_core_hash_destroy(&verto_globals.jsock_hash); + ks_global_set_logger(NULL); + ks_shutdown(); + return SWITCH_STATUS_SUCCESS; } @@ -6283,7 +6915,6 @@ SWITCH_MODULE_RUNTIME_FUNCTION(mod_verto_runtime) return SWITCH_STATUS_TERM; } - /* For Emacs: * Local Variables: * mode:c diff --git a/src/mod/endpoints/mod_verto/mod_verto.h b/src/mod/endpoints/mod_verto/mod_verto.h index 1bf8d0cdb5..f3326f605d 100644 --- a/src/mod/endpoints/mod_verto/mod_verto.h +++ b/src/mod/endpoints/mod_verto/mod_verto.h @@ -62,6 +62,8 @@ #include #include "mcast.h" +#include "ks.h" + #define MAX_QUEUE_LEN 100000 #define MAX_MISSED 500 @@ -93,16 +95,18 @@ typedef enum { JPFLAG_CHECK_ATTACH = (1 << 2), JPFLAG_EVENTS = (1 << 3), JPFLAG_AUTH_EVENTS = (1 << 4), - JPFLAG_ALL_EVENTS_AUTHED = (1 << 5) + JPFLAG_ALL_EVENTS_AUTHED = (1 << 5), + JPFLAG_AUTH_EXPIRED = (1 << 6) } jpflag_t; struct verto_profile_s; struct jsock_s { - ws_socket_t client_socket; + ks_socket_t client_socket; switch_memory_pool_t *pool; switch_thread_t *thread; - wsh_t ws; + ks_pool_t *kpool; + kws_t *ws; unsigned char buf[65535]; char *name; jsock_type_t ptype; @@ -111,10 +115,11 @@ struct jsock_s { #ifndef WIN32 struct passwd pw; #endif - + uint32_t attach_timer; + uint8_t drop; uint8_t nodelete; - ws_socket_t local_sock; + ks_socket_t local_sock; SSL *ssl; jpflag_t flags; @@ -136,12 +141,14 @@ struct jsock_s { char remote_host[256]; int remote_port; int family; - + time_t exptime; + time_t logintime; struct verto_profile_s *profile; switch_thread_rwlock_t *rwlock; switch_mutex_t *write_mutex; switch_mutex_t *filter_mutex; + switch_mutex_t *flag_mutex; switch_event_t *params; switch_event_t *vars; @@ -230,19 +237,22 @@ struct verto_profile_s { jsock_t *jsock_head; int jsock_count; - ws_socket_t server_socket[MAX_BIND]; + ks_socket_t server_socket[MAX_BIND]; int running; int ssl_ready; int ready; int debug; - + int chop_domain; + int in_thread; int blind_reg; char *userauth; char *root_passwd; + int send_passwd; + char *context; char *dialplan; @@ -304,9 +314,11 @@ struct globals_s { int debug; int ready; + int send_passwd; int profile_threads; int enable_presence; int enable_fs_events; + switch_bool_t kslog_on; switch_hash_t *jsock_hash; switch_mutex_t *jsock_mutex; @@ -322,6 +334,9 @@ struct globals_s { uint32_t detach_timeout; switch_event_channel_id_t event_channel_id; + + switch_log_level_t debug_level; + }; diff --git a/src/mod/endpoints/mod_verto/ws.c b/src/mod/endpoints/mod_verto/ws.c deleted file mode 100644 index 122b6433c0..0000000000 --- a/src/mod/endpoints/mod_verto/ws.c +++ /dev/null @@ -1,1097 +0,0 @@ -#include -#include "ws.h" -#include - -#ifndef _MSC_VER -#include -#endif - -#if defined(__linux__) || defined(__GLIBC__) -#include -#endif - -#ifndef _MSC_VER -#define ms_sleep(x) usleep( x * 1000); -#else -#define ms_sleep(x) Sleep( x ); -#endif - -#ifdef _MSC_VER -/* warning C4706: assignment within conditional expression*/ -#pragma warning(disable: 4706) -#endif - -#define WS_BLOCK 1 -#define WS_NOBLOCK 0 - -#define WS_INIT_SANITY 5000 -#define WS_WRITE_SANITY 200 - -#define SHA1_HASH_SIZE 20 -static struct ws_globals_s ws_globals; - -#ifndef WSS_STANDALONE - -void init_ssl(void) -{ - // SSL_library_init(); -} -void deinit_ssl(void) -{ - return; -} - -#else -static void pthreads_thread_id(CRYPTO_THREADID *id); -static void pthreads_locking_callback(int mode, int type, const char *file, int line); - -static pthread_mutex_t *lock_cs; -static long *lock_count; - - - -static void thread_setup(void) -{ - int i; - - lock_cs = OPENSSL_malloc(CRYPTO_num_locks() * sizeof(pthread_mutex_t)); - lock_count = OPENSSL_malloc(CRYPTO_num_locks() * sizeof(long)); - - for (i = 0; i < CRYPTO_num_locks(); i++) { - lock_count[i] = 0; - pthread_mutex_init(&(lock_cs[i]), NULL); - } - - CRYPTO_THREADID_set_callback(pthreads_thread_id); - CRYPTO_set_locking_callback(pthreads_locking_callback); -} - -static void thread_cleanup(void) -{ - int i; - - CRYPTO_set_locking_callback(NULL); - - for (i=0; i buflen - 1) { - cplen = buflen -1; - } else { - cplen = len; - } - - strncpy(buf, v, cplen); - *(buf+cplen) = '\0'; - return 1; - } - - } - } - return 0; -} - -static int b64encode(unsigned char *in, size_t ilen, unsigned char *out, size_t olen) -{ - int y=0,bytes=0; - size_t x=0; - unsigned int b=0,l=0; - - if(olen) { - } - - for(x=0;x= 6) { - out[bytes++] = c64[(b>>(l-=6))%64]; - if(++y!=72) { - continue; - } - //out[bytes++] = '\n'; - y=0; - } - } - - if (l > 0) { - out[bytes++] = c64[((b%16)<<(6-l))%64]; - } - if (l != 0) while (l < 6) { - out[bytes++] = '=', l += 2; - } - - return 0; -} - -#ifdef NO_OPENSSL -static void sha1_digest(char *digest, unsigned char *in) -{ - SHA1Context sha; - char *p; - int x; - - - SHA1Init(&sha); - SHA1Update(&sha, in, strlen(in)); - SHA1Final(&sha, digest); -} -#else - -static void sha1_digest(unsigned char *digest, char *in) -{ - SHA_CTX sha; - - SHA1_Init(&sha); - SHA1_Update(&sha, in, strlen(in)); - SHA1_Final(digest, &sha); - -} - -#endif - -int ws_handshake(wsh_t *wsh) -{ - char key[256] = ""; - char version[5] = ""; - char proto[256] = ""; - char proto_buf[384] = ""; - char input[512] = ""; - unsigned char output[SHA1_HASH_SIZE] = ""; - char b64[256] = ""; - char respond[1024] = ""; - ssize_t bytes; - char *p, *e = 0; - - if (wsh->sock == ws_sock_invalid) { - return -3; - } - - while((bytes = ws_raw_read(wsh, wsh->buffer + wsh->datalen, wsh->buflen - wsh->datalen, WS_BLOCK)) > 0) { - wsh->datalen += bytes; - if (strstr(wsh->buffer, "\r\n\r\n") || strstr(wsh->buffer, "\n\n")) { - break; - } - } - - if (bytes < 0 || bytes > wsh->buflen -1) { - goto err; - } - - *(wsh->buffer + wsh->datalen) = '\0'; - - if (strncasecmp(wsh->buffer, "GET ", 4)) { - goto err; - } - - p = wsh->buffer + 4; - - e = strchr(p, ' '); - if (!e) { - goto err; - } - - wsh->uri = malloc((e-p) + 1); - - if (!wsh->uri) goto err; - - strncpy(wsh->uri, p, e-p); - *(wsh->uri + (e-p)) = '\0'; - - cheezy_get_var(wsh->buffer, "Sec-WebSocket-Key", key, sizeof(key)); - cheezy_get_var(wsh->buffer, "Sec-WebSocket-Version", version, sizeof(version)); - cheezy_get_var(wsh->buffer, "Sec-WebSocket-Protocol", proto, sizeof(proto)); - - if (!*key) { - goto err; - } - - snprintf(input, sizeof(input), "%s%s", key, WEBSOCKET_GUID); - sha1_digest(output, input); - b64encode((unsigned char *)output, SHA1_HASH_SIZE, (unsigned char *)b64, sizeof(b64)); - - if (*proto) { - snprintf(proto_buf, sizeof(proto_buf), "Sec-WebSocket-Protocol: %s\r\n", proto); - } - - snprintf(respond, sizeof(respond), - "HTTP/1.1 101 Switching Protocols\r\n" - "Upgrade: websocket\r\n" - "Connection: Upgrade\r\n" - "Sec-WebSocket-Accept: %s\r\n" - "%s\r\n", - b64, - proto_buf); - respond[511] = 0; - - if (ws_raw_write(wsh, respond, strlen(respond)) != (ssize_t)strlen(respond)) { - goto err; - } - - wsh->handshake = 1; - - return 0; - - err: - - if (!wsh->stay_open) { - - if (bytes > 0) { - snprintf(respond, sizeof(respond), "HTTP/1.1 400 Bad Request\r\n" - "Sec-WebSocket-Version: 13\r\n\r\n"); - respond[511] = 0; - - ws_raw_write(wsh, respond, strlen(respond)); - } - - ws_close(wsh, WS_NONE); - } - - return -1; - -} - -#define SSL_WANT_READ_WRITE(err) (err == SSL_ERROR_WANT_READ || err == SSL_ERROR_WANT_WRITE) - -ssize_t ws_raw_read(wsh_t *wsh, void *data, size_t bytes, int block) -{ - ssize_t r; - int ssl_err = 0; - - wsh->x++; - if (wsh->x > 250) ms_sleep(1); - - if (wsh->ssl) { - do { - r = SSL_read(wsh->ssl, data, bytes); - - if (r < 0) { - ssl_err = SSL_get_error(wsh->ssl, r); - - if (SSL_WANT_READ_WRITE(ssl_err)) { - if (!block) { - r = -2; - goto end; - } - wsh->x++; - ms_sleep(10); - } else { - r = -1; - goto end; - } - } - - } while (r < 0 && SSL_WANT_READ_WRITE(ssl_err) && wsh->x < 1000); - - goto end; - } - - do { - - r = recv(wsh->sock, data, bytes, 0); - - if (r == -1) { - if (!block && xp_is_blocking(xp_errno())) { - r = -2; - goto end; - } - - if (block) { - wsh->x++; - ms_sleep(10); - } - } - } while (r == -1 && xp_is_blocking(xp_errno()) && wsh->x < 1000); - - end: - - if (wsh->x >= 10000 || (block && wsh->x >= 1000)) { - r = -1; - } - - if (r > 0) { - *((char *)data + r) = '\0'; - } - - if (r >= 0) { - wsh->x = 0; - } - - return r; -} - -/* - * Blocking read until bytes have been received, failure, or too many retries. - */ -static ssize_t ws_raw_read_blocking(wsh_t *wsh, char *data, size_t max_bytes, int max_retries) -{ - ssize_t total_bytes_read = 0; - while (total_bytes_read < max_bytes && max_retries-- > 0) { - ssize_t bytes_read = ws_raw_read(wsh, data + total_bytes_read, max_bytes - total_bytes_read, WS_BLOCK); - if (bytes_read < 0) { - break; - } - total_bytes_read += bytes_read; - } - return total_bytes_read; -} - - -ssize_t ws_raw_write(wsh_t *wsh, void *data, size_t bytes) -{ - ssize_t r; - int sanity = WS_WRITE_SANITY; - int ssl_err = 0; - size_t wrote = 0; - - if (wsh->ssl) { - do { - r = SSL_write(wsh->ssl, (void *)((unsigned char *)data + wrote), bytes - wrote); - - if (r == 0) { - ssl_err = 42; - break; - } - - if (r > 0) { - wrote += r; - } - - if (sanity < WS_WRITE_SANITY) { - int ms = 1; - - if (wsh->block) { - if (sanity < WS_WRITE_SANITY / 2) { - ms = 25; - } else if (sanity < WS_WRITE_SANITY * 3 / 4) { - ms = 50; - } - } - ms_sleep(ms); - } - - if (r < 0) { - ssl_err = SSL_get_error(wsh->ssl, r); - - if (!SSL_WANT_READ_WRITE(ssl_err)) { - break; - } - ssl_err = 0; - } - - } while (--sanity > 0 && wrote < bytes); - - if (!sanity) ssl_err = 56; - - if (ssl_err) { - r = ssl_err * -1; - } - - return r; - } - - do { - r = send(wsh->sock, (void *)((unsigned char *)data + wrote), bytes - wrote, 0); - - if (r > 0) { - wrote += r; - } - - if (sanity < WS_WRITE_SANITY) { - int ms = 1; - - if (wsh->block) { - if (sanity < WS_WRITE_SANITY / 2) { - ms = 25; - } else if (sanity < WS_WRITE_SANITY * 3 / 4) { - ms = 50; - } - } - ms_sleep(ms); - } - - if (r == -1) { - if (!xp_is_blocking(xp_errno())) { - break; - } - } - - } while (--sanity > 0 && wrote < bytes); - - //if (r<0) { - //printf("wRITE FAIL: %s\n", strerror(errno)); - //} - - return r < 0 ? r : wrote; -} - -#ifdef _MSC_VER -static int setup_socket(ws_socket_t sock) -{ - unsigned long v = 1; - - if (ioctlsocket(sock, FIONBIO, &v) == SOCKET_ERROR) { - return -1; - } - - return 0; - -} - -static int restore_socket(ws_socket_t sock) -{ - unsigned long v = 0; - - if (ioctlsocket(sock, FIONBIO, &v) == SOCKET_ERROR) { - return -1; - } - - return 0; - -} - -#else - -static int setup_socket(ws_socket_t sock) -{ - int flags = fcntl(sock, F_GETFL, 0); - return fcntl(sock, F_SETFL, flags | O_NONBLOCK); -} - -static int restore_socket(ws_socket_t sock) -{ - int flags = fcntl(sock, F_GETFL, 0); - - flags &= ~O_NONBLOCK; - - return fcntl(sock, F_SETFL, flags); - -} - -#endif - - -int establish_logical_layer(wsh_t *wsh) -{ - - if (!wsh->sanity) { - return -1; - } - - if (wsh->logical_established) { - return 0; - } - - if (wsh->secure && !wsh->secure_established) { - int code; - - if (!wsh->ssl) { - wsh->ssl = SSL_new(wsh->ssl_ctx); - assert(wsh->ssl); - - SSL_set_fd(wsh->ssl, wsh->sock); - } - - do { - code = SSL_accept(wsh->ssl); - - if (code == 1) { - wsh->secure_established = 1; - break; - } - - if (code == 0) { - return -1; - } - - if (code < 0) { - int ssl_err = SSL_get_error(wsh->ssl, code); - if (!SSL_WANT_READ_WRITE(ssl_err)) { - return -1; - } - } - - if (wsh->block) { - ms_sleep(10); - } else { - ms_sleep(1); - } - - wsh->sanity--; - - if (!wsh->block) { - return -2; - } - - } while (wsh->sanity > 0); - - if (!wsh->sanity) { - return -1; - } - - } - - while (!wsh->down && !wsh->handshake) { - int r = ws_handshake(wsh); - - if (r < 0) { - wsh->down = 1; - return -1; - } - - if (!wsh->handshake && !wsh->block) { - return -2; - } - - } - - wsh->logical_established = 1; - - return 0; -} - - -int ws_init(wsh_t *wsh, ws_socket_t sock, SSL_CTX *ssl_ctx, int close_sock, int block, int stay_open) -{ - memset(wsh, 0, sizeof(*wsh)); - - wsh->sock = sock; - wsh->block = block; - wsh->sanity = WS_INIT_SANITY; - wsh->ssl_ctx = ssl_ctx; - wsh->stay_open = stay_open; - - if (!ssl_ctx) { - ssl_ctx = ws_globals.ssl_ctx; - } - - if (close_sock) { - wsh->close_sock = 1; - } - - wsh->buflen = 1024 * 64; - wsh->bbuflen = wsh->buflen; - - wsh->buffer = malloc(wsh->buflen); - wsh->bbuffer = malloc(wsh->bbuflen); - //printf("init %p %ld\n", (void *) wsh->bbuffer, wsh->bbuflen); - //memset(wsh->buffer, 0, wsh->buflen); - //memset(wsh->bbuffer, 0, wsh->bbuflen); - - wsh->secure = ssl_ctx ? 1 : 0; - - setup_socket(sock); - - if (establish_logical_layer(wsh) == -1) { - return -1; - } - - if (wsh->down) { - return -1; - } - - return 0; -} - -void ws_destroy(wsh_t *wsh) -{ - - if (!wsh) { - return; - } - - if (!wsh->down) { - ws_close(wsh, WS_NONE); - } - - if (wsh->down > 1) { - return; - } - - wsh->down = 2; - - if (wsh->write_buffer) { - free(wsh->write_buffer); - wsh->write_buffer = NULL; - wsh->write_buffer_len = 0; - } - - if (wsh->ssl) { - SSL_free(wsh->ssl); - wsh->ssl = NULL; - } - - if (wsh->buffer) free(wsh->buffer); - if (wsh->bbuffer) free(wsh->bbuffer); - - wsh->buffer = wsh->bbuffer = NULL; - -} - -ssize_t ws_close(wsh_t *wsh, int16_t reason) -{ - - if (wsh->down) { - return -1; - } - - wsh->down = 1; - - if (wsh->uri) { - free(wsh->uri); - wsh->uri = NULL; - } - - if (reason && wsh->sock != ws_sock_invalid) { - uint16_t *u16; - uint8_t fr[4] = {WSOC_CLOSE | 0x80, 2, 0}; - - u16 = (uint16_t *) &fr[2]; - *u16 = htons((int16_t)reason); - ws_raw_write(wsh, fr, 4); - } - - if (wsh->ssl && wsh->sock != ws_sock_invalid) { - /* first invocation of SSL_shutdown() would normally return 0 and just try to send SSL protocol close request. - we just slightly polite, since we want to close socket fast and - not bother waiting for SSL protocol close response before closing socket, - since we want cleanup to be done fast for scenarios like: - client change NAT (like jump from one WiFi to another) and now unreachable from old ip:port, however - immidiately reconnect with new ip:port but old session id (and thus should replace the old session/channel) - */ - SSL_shutdown(wsh->ssl); - } - - /* restore to blocking here, so any further read/writes will block */ - restore_socket(wsh->sock); - - if (wsh->close_sock && wsh->sock != ws_sock_invalid) { - /* signal socket to shutdown() before close(): FIN-ACK-FIN-ACK insead of RST-RST - do not really handle errors here since it all going to die anyway. - all buffered writes if any(like SSL_shutdown() ones) will still be sent. - */ -#ifndef WIN32 - shutdown(wsh->sock, SHUT_RDWR); - close(wsh->sock); -#else - shutdown(wsh->sock, SD_BOTH); - closesocket(wsh->sock); -#endif - } - - wsh->sock = ws_sock_invalid; - - return reason * -1; - -} - - -uint64_t hton64(uint64_t val) -{ - if (__BYTE_ORDER == __BIG_ENDIAN) return (val); - else return __bswap_64(val); -} - -uint64_t ntoh64(uint64_t val) -{ - if (__BYTE_ORDER == __BIG_ENDIAN) return (val); - else return __bswap_64(val); -} - - -ssize_t ws_read_frame(wsh_t *wsh, ws_opcode_t *oc, uint8_t **data) -{ - - ssize_t need = 2; - char *maskp; - int ll = 0; - int frag = 0; - int blen; - - wsh->body = wsh->bbuffer; - wsh->packetlen = 0; - - again: - need = 2; - maskp = NULL; - *data = NULL; - - ll = establish_logical_layer(wsh); - - if (ll < 0) { - return ll; - } - - if (wsh->down) { - return -1; - } - - if (!wsh->handshake) { - return ws_close(wsh, WS_NONE); - } - - if ((wsh->datalen = ws_raw_read(wsh, wsh->buffer, 9, wsh->block)) < 0) { - if (wsh->datalen == -2) { - return -2; - } - return ws_close(wsh, WS_NONE); - } - - if (wsh->datalen < need) { - ssize_t bytes = ws_raw_read(wsh, wsh->buffer + wsh->datalen, 9 - wsh->datalen, WS_BLOCK); - if (bytes < 0 || (wsh->datalen += bytes) < need) { - /* too small - protocol err */ - return ws_close(wsh, WS_NONE); - } - } - - *oc = *wsh->buffer & 0xf; - - switch(*oc) { - case WSOC_CLOSE: - { - wsh->plen = wsh->buffer[1] & 0x7f; - *data = (uint8_t *) &wsh->buffer[2]; - return ws_close(wsh, WS_RECV_CLOSE); - } - break; - case WSOC_CONTINUATION: - case WSOC_TEXT: - case WSOC_BINARY: - case WSOC_PING: - case WSOC_PONG: - { - int fin = (wsh->buffer[0] >> 7) & 1; - int mask = (wsh->buffer[1] >> 7) & 1; - - - if (!fin && *oc != WSOC_CONTINUATION) { - frag = 1; - } else if (fin && *oc == WSOC_CONTINUATION) { - frag = 0; - } - - if (mask) { - need += 4; - - if (need > wsh->datalen) { - ssize_t bytes = ws_raw_read_blocking(wsh, wsh->buffer + wsh->datalen, need - wsh->datalen, 10); - if (bytes < 0 || (wsh->datalen += bytes) < need) { - /* too small - protocol err */ - *oc = WSOC_CLOSE; - return ws_close(wsh, WS_NONE); - } - } - } - - wsh->plen = wsh->buffer[1] & 0x7f; - wsh->payload = &wsh->buffer[2]; - - if (wsh->plen == 127) { - uint64_t *u64; - - need += 8; - - if (need > wsh->datalen) { - ssize_t bytes = ws_raw_read_blocking(wsh, wsh->buffer + wsh->datalen, need - wsh->datalen, 10); - if (bytes < 0 || (wsh->datalen += bytes) < need) { - /* too small - protocol err */ - *oc = WSOC_CLOSE; - return ws_close(wsh, WS_NONE); - } - } - - u64 = (uint64_t *) wsh->payload; - wsh->payload += 8; - wsh->plen = ntoh64(*u64); - } else if (wsh->plen == 126) { - uint16_t *u16; - - need += 2; - - if (need > wsh->datalen) { - ssize_t bytes = ws_raw_read_blocking(wsh, wsh->buffer + wsh->datalen, need - wsh->datalen, 10); - if (bytes < 0 || (wsh->datalen += bytes) < need) { - /* too small - protocol err */ - *oc = WSOC_CLOSE; - return ws_close(wsh, WS_NONE); - } - } - - u16 = (uint16_t *) wsh->payload; - wsh->payload += 2; - wsh->plen = ntohs(*u16); - } - - if (mask) { - maskp = (char *)wsh->payload; - wsh->payload += 4; - } - - need = (wsh->plen - (wsh->datalen - need)); - - if (need < 0) { - /* invalid read - protocol err .. */ - *oc = WSOC_CLOSE; - return ws_close(wsh, WS_NONE); - } - - blen = wsh->body - wsh->bbuffer; - - if (need + blen > (ssize_t)wsh->bbuflen) { - void *tmp; - - wsh->bbuflen = need + blen + wsh->rplen; - - if ((tmp = realloc(wsh->bbuffer, wsh->bbuflen))) { - wsh->bbuffer = tmp; - } else { - abort(); - } - - wsh->body = wsh->bbuffer + blen; - } - - wsh->rplen = wsh->plen - need; - - if (wsh->rplen) { - memcpy(wsh->body, wsh->payload, wsh->rplen); - } - - while(need) { - ssize_t r = ws_raw_read(wsh, wsh->body + wsh->rplen, need, WS_BLOCK); - - if (r < 1) { - /* invalid read - protocol err .. */ - *oc = WSOC_CLOSE; - return ws_close(wsh, WS_NONE); - } - - wsh->datalen += r; - wsh->rplen += r; - need -= r; - } - - if (mask && maskp) { - ssize_t i; - - for (i = 0; i < wsh->datalen; i++) { - wsh->body[i] ^= maskp[i % 4]; - } - } - - - if (*oc == WSOC_PING) { - ws_write_frame(wsh, WSOC_PONG, wsh->body, wsh->rplen); - goto again; - } - - *(wsh->body+wsh->rplen) = '\0'; - wsh->packetlen += wsh->rplen; - wsh->body += wsh->rplen; - - if (frag) { - goto again; - } - - *data = (uint8_t *)wsh->bbuffer; - - //printf("READ[%ld][%d]-----------------------------:\n[%s]\n-------------------------------\n", wsh->packetlen, *oc, (char *)*data); - - - return wsh->packetlen; - } - break; - default: - { - /* invalid op code - protocol err .. */ - *oc = WSOC_CLOSE; - return ws_close(wsh, WS_PROTO_ERR); - } - break; - } -} - -ssize_t ws_write_frame(wsh_t *wsh, ws_opcode_t oc, void *data, size_t bytes) -{ - uint8_t hdr[14] = { 0 }; - size_t hlen = 2; - uint8_t *bp; - ssize_t raw_ret = 0; - - if (wsh->down) { - return -1; - } - - //printf("WRITE[%ld]-----------------------------:\n[%s]\n-----------------------------------\n", bytes, (char *) data); - - hdr[0] = (uint8_t)(oc | 0x80); - - if (bytes < 126) { - hdr[1] = (uint8_t)bytes; - } else if (bytes < 0x10000) { - uint16_t *u16; - - hdr[1] = 126; - hlen += 2; - - u16 = (uint16_t *) &hdr[2]; - *u16 = htons((uint16_t) bytes); - - } else { - uint64_t *u64; - - hdr[1] = 127; - hlen += 8; - - u64 = (uint64_t *) &hdr[2]; - *u64 = hton64(bytes); - } - - if (wsh->write_buffer_len < (hlen + bytes + 1)) { - void *tmp; - - wsh->write_buffer_len = hlen + bytes + 1; - if ((tmp = realloc(wsh->write_buffer, wsh->write_buffer_len))) { - wsh->write_buffer = tmp; - } else { - abort(); - } - } - - bp = (uint8_t *) wsh->write_buffer; - memcpy(bp, (void *) &hdr[0], hlen); - memcpy(bp + hlen, data, bytes); - - raw_ret = ws_raw_write(wsh, bp, (hlen + bytes)); - - if (raw_ret != (ssize_t) (hlen + bytes)) { - return raw_ret; - } - - return bytes; -} - -#ifdef _MSC_VER - -int xp_errno(void) -{ - return WSAGetLastError(); -} - -int xp_is_blocking(int errcode) -{ - return errcode == WSAEWOULDBLOCK || errcode == WSAEINPROGRESS; -} - -#else - -int xp_errno(void) -{ - return errno; -} - -int xp_is_blocking(int errcode) -{ - return errcode == EAGAIN || errcode == EWOULDBLOCK || errcode == EINPROGRESS || errcode == EINTR || errcode == ETIMEDOUT; -} - -#endif diff --git a/src/mod/endpoints/mod_verto/ws.h b/src/mod/endpoints/mod_verto/ws.h deleted file mode 100644 index 84127cfb2c..0000000000 --- a/src/mod/endpoints/mod_verto/ws.h +++ /dev/null @@ -1,143 +0,0 @@ -#ifndef _WS_H -#define _WS_H - -//#define WSS_STANDALONE 1 - -#define WEBSOCKET_GUID "258EAFA5-E914-47DA-95CA-C5AB0DC85B11" -#define B64BUFFLEN 1024 - -#include -#ifndef _MSC_VER -#include -#include -#include -#include -#else -#pragma warning(disable:4996) -#endif -#include -#include -#include -#include -#include -#include -#include -//#include "sha1.h" -#include - -#if defined(_MSC_VER) || defined(__APPLE__) || defined(__FreeBSD__) || (defined(__SVR4) && defined(__sun)) -#define __bswap_64(x) \ - x = (x>>56) | \ - ((x<<40) & 0x00FF000000000000) | \ - ((x<<24) & 0x0000FF0000000000) | \ - ((x<<8) & 0x000000FF00000000) | \ - ((x>>8) & 0x00000000FF000000) | \ - ((x>>24) & 0x0000000000FF0000) | \ - ((x>>40) & 0x000000000000FF00) | \ - (x<<56) -#endif -#ifdef _MSC_VER -#ifndef strncasecmp -#define strncasecmp _strnicmp -#endif -#ifdef _WIN64 -#define WS_SSIZE_T __int64 -#elif _MSC_VER >= 1400 -#define WS_SSIZE_T __int32 __w64 -#else -#define WS_SSIZE_T __int32 -#endif -typedef WS_SSIZE_T ssize_t; -#endif - - -struct ws_globals_s { - const SSL_METHOD *ssl_method; - SSL_CTX *ssl_ctx; - char cert[512]; - char key[512]; -}; - -//extern struct ws_globals_s ws_globals; - -#ifndef WIN32 -typedef int ws_socket_t; -#else -typedef SOCKET ws_socket_t; -#endif -#define ws_sock_invalid (ws_socket_t)-1 - - -typedef enum { - WS_NONE = 0, - WS_RECV_CLOSE = 1000, - WS_PROTO_ERR = 1002, - WS_DATA_TOO_BIG = 1009 -} ws_cause_t; - -typedef enum { - WSOC_CONTINUATION = 0x0, - WSOC_TEXT = 0x1, - WSOC_BINARY = 0x2, - WSOC_CLOSE = 0x8, - WSOC_PING = 0x9, - WSOC_PONG = 0xA -} ws_opcode_t; - -typedef struct wsh_s { - ws_socket_t sock; - char *buffer; - char *bbuffer; - char *body; - char *uri; - size_t buflen; - size_t bbuflen; - ssize_t datalen; - ssize_t wdatalen; - char *payload; - ssize_t plen; - ssize_t rplen; - ssize_t packetlen; - SSL *ssl; - int handshake; - uint8_t down; - int secure; - uint8_t close_sock; - SSL_CTX *ssl_ctx; - int block; - int sanity; - int secure_established; - int logical_established; - int stay_open; - int x; - void *write_buffer; - size_t write_buffer_len; -} wsh_t; - -ssize_t ws_send_buf(wsh_t *wsh, ws_opcode_t oc); -ssize_t ws_feed_buf(wsh_t *wsh, void *data, size_t bytes); - - -ssize_t ws_raw_read(wsh_t *wsh, void *data, size_t bytes, int block); -ssize_t ws_raw_write(wsh_t *wsh, void *data, size_t bytes); -ssize_t ws_read_frame(wsh_t *wsh, ws_opcode_t *oc, uint8_t **data); -ssize_t ws_write_frame(wsh_t *wsh, ws_opcode_t oc, void *data, size_t bytes); -int ws_init(wsh_t *wsh, ws_socket_t sock, SSL_CTX *ssl_ctx, int close_sock, int block, int stay_open); -ssize_t ws_close(wsh_t *wsh, int16_t reason); -void ws_destroy(wsh_t *wsh); -void init_ssl(void); -void deinit_ssl(void); -int xp_errno(void); -int xp_is_blocking(int errcode); - - - -#ifndef _MSC_VER -static inline uint64_t get_unaligned_uint64(const void *p) -{ - const struct { uint64_t d; } __attribute__((packed)) *pp = p; - return pp->d; -} -#endif - -#endif diff --git a/src/mod/event_handlers/mod_amqp/mod_amqp.h b/src/mod/event_handlers/mod_amqp/mod_amqp.h index 53ea03836c..0717876040 100644 --- a/src/mod/event_handlers/mod_amqp/mod_amqp.h +++ b/src/mod/event_handlers/mod_amqp/mod_amqp.h @@ -43,6 +43,7 @@ #include #include #include +#include #ifndef _MSC_VER #include @@ -74,6 +75,8 @@ typedef struct mod_amqp_connection_s { char *password; unsigned int port; unsigned int heartbeat; /* in seconds */ + amqp_boolean_t ssl_on; + amqp_boolean_t ssl_verify_peer; amqp_connection_state_t state; struct mod_amqp_connection_s *next; diff --git a/src/mod/event_handlers/mod_amqp/mod_amqp_command.c b/src/mod/event_handlers/mod_amqp/mod_amqp_command.c index c98c123c07..2789a6e252 100644 --- a/src/mod/event_handlers/mod_amqp/mod_amqp_command.c +++ b/src/mod/event_handlers/mod_amqp/mod_amqp_command.c @@ -274,11 +274,11 @@ static void mod_amqp_command_response(mod_amqp_command_profile_t *profile, char void * SWITCH_THREAD_FUNC mod_amqp_command_thread(switch_thread_t *thread, void *data) { + amqp_bytes_t queueName = { 0, NULL }; mod_amqp_command_profile_t *profile = (mod_amqp_command_profile_t *) data; while (profile->running) { amqp_queue_declare_ok_t *recv_queue; - amqp_bytes_t queueName = { 0, NULL }; /* Ensure we have an AMQP connection */ if (!profile->conn_active) { diff --git a/src/mod/event_handlers/mod_amqp/mod_amqp_connection.c b/src/mod/event_handlers/mod_amqp/mod_amqp_connection.c index 1da96328f9..91feec93d5 100644 --- a/src/mod/event_handlers/mod_amqp/mod_amqp_connection.c +++ b/src/mod/event_handlers/mod_amqp/mod_amqp_connection.c @@ -116,6 +116,14 @@ switch_status_t mod_amqp_connection_open(mod_amqp_connection_t *connections, mod amqp_status = -1; while (connection_attempt && amqp_status){ + if (connection_attempt->ssl_on == 1) { + amqp_set_initialize_ssl_library(connection_attempt->ssl_on); + if (!(socket = amqp_ssl_socket_new(newConnection))) { + switch_log_printf(SWITCH_CHANNEL_LOG, SWITCH_LOG_CRIT, "Could not create SSL socket\n"); + goto err; + } + amqp_ssl_socket_set_verify_peer(socket, connection_attempt->ssl_verify_peer); + } switch_log_printf(SWITCH_CHANNEL_LOG, SWITCH_LOG_DEBUG, "Profile[%s] trying to connect to AMQP broker %s:%d\n", profile_name, connection_attempt->hostname, connection_attempt->port); @@ -191,6 +199,8 @@ switch_status_t mod_amqp_connection_create(mod_amqp_connection_t **conn, switch_ char *name = (char *) switch_xml_attr_soft(cfg, "name"); char *hostname = NULL, *virtualhost = NULL, *username = NULL, *password = NULL; unsigned int port = 0, heartbeat = 0; + amqp_boolean_t ssl_on = 0; + amqp_boolean_t ssl_verify_peer = 1; if (zstr(name)) { switch_log_printf(SWITCH_CHANNEL_LOG, SWITCH_LOG_CRIT, "Connection missing name attribute\n%s\n", switch_xml_toxml(cfg, 1)); @@ -233,6 +243,10 @@ switch_status_t mod_amqp_connection_create(mod_amqp_connection_t **conn, switch_ if (interval && interval > 0) { heartbeat = interval; } + } else if (!strncmp(var, "ssl_on", 3) && switch_true(val) == SWITCH_TRUE) { + ssl_on = 1; + } else if (!strncmp(var, "ssl_verify_peer", 15) && switch_true(val) == SWITCH_FALSE) { + ssl_verify_peer = 0; } } @@ -242,6 +256,8 @@ switch_status_t mod_amqp_connection_create(mod_amqp_connection_t **conn, switch_ new_con->password = password ? password : "guest"; new_con->port = port ? port : 5672; new_con->heartbeat = heartbeat ? heartbeat : 0; + new_con->ssl_on = ssl_on; + new_con->ssl_verify_peer = ssl_verify_peer; *conn = new_con; return SWITCH_STATUS_SUCCESS; diff --git a/src/mod/event_handlers/mod_amqp/mod_amqp_utils.c b/src/mod/event_handlers/mod_amqp/mod_amqp_utils.c index 7ebcff6e3f..03a0f262c0 100644 --- a/src/mod/event_handlers/mod_amqp/mod_amqp_utils.c +++ b/src/mod/event_handlers/mod_amqp/mod_amqp_utils.c @@ -193,6 +193,7 @@ switch_status_t mod_amqp_do_config(switch_bool_t reload) switch_log_printf(SWITCH_CHANNEL_LOG, SWITCH_LOG_WARNING, "Unable to locate logging section for mod_amqp\n" ); } + switch_xml_free(xml); return SWITCH_STATUS_SUCCESS; } diff --git a/src/mod/event_handlers/mod_cdr_mongodb/driver/src/mongo.c b/src/mod/event_handlers/mod_cdr_mongodb/driver/src/mongo.c index 77870b3dc2..19110f2e66 100644 --- a/src/mod/event_handlers/mod_cdr_mongodb/driver/src/mongo.c +++ b/src/mod/event_handlers/mod_cdr_mongodb/driver/src/mongo.c @@ -438,7 +438,7 @@ static void mongo_replset_add_node( mongo_host_port **list, const char *host, in mongo_host_port *host_port = bson_malloc( sizeof( mongo_host_port ) ); host_port->port = port; host_port->next = NULL; - strncpy( host_port->host, host, sizeof(host_port->host) - 1 ); + snprintf(host_port->host, sizeof(host_port->host), "%s", host); if( *list == NULL ) *list = host_port; diff --git a/src/mod/event_handlers/mod_event_multicast/mod_event_multicast.c b/src/mod/event_handlers/mod_event_multicast/mod_event_multicast.c index f9fa8ff02b..1ebf5cb7fe 100644 --- a/src/mod/event_handlers/mod_event_multicast/mod_event_multicast.c +++ b/src/mod/event_handlers/mod_event_multicast/mod_event_multicast.c @@ -24,6 +24,7 @@ * Contributor(s): * * Anthony Minessale II + * Nick Lemberger * * * mod_event_multicast.c -- Multicast Events @@ -35,6 +36,7 @@ #endif #define MULTICAST_BUFFSIZE 65536 +#define MAX_DST_HOSTS 16 /* magic byte sequence */ static unsigned char MAGIC[] = { 226, 132, 177, 197, 152, 198, 142, 211, 172, 197, 158, 208, 169, 208, 135, 197, 166, 207, 154, 196, 166 }; @@ -46,22 +48,50 @@ SWITCH_MODULE_RUNTIME_FUNCTION(mod_event_multicast_runtime); SWITCH_MODULE_DEFINITION(mod_event_multicast, mod_event_multicast_load, mod_event_multicast_shutdown, mod_event_multicast_runtime); static switch_memory_pool_t *module_pool = NULL; +static char *addr_type_names[] = { "IPv4 unicast", "IPv4 multicast", "IPv6 unicast", "IPv6 multicast", "Unknown" }; + +typedef enum { + IPV4_UNICAST, + IPV4_MULTICAST, + IPV6_UNICAST, + IPV6_MULTICAST, + IP_UNKOWN_TYPE +} addr_type_t; + +typedef struct { + char *ipaddr; + switch_sockaddr_t *sockaddr; + addr_type_t addrtype; +} dst_sockaddr_t; static struct { - char *address; + char *src_addr; + char *src_addr6; + char *dst_addrs; char *bindings; uint32_t key_count; switch_port_t port; - switch_sockaddr_t *addr; + int has_udp; + int has_udp6; + switch_sockaddr_t *src_sockaddr; + switch_sockaddr_t *src_sockaddr6; switch_socket_t *udp_socket; + switch_socket_t *udp_socket6; switch_hash_t *event_hash; uint8_t event_list[SWITCH_EVENT_ALL + 1]; int running; + int runtime_thread_has_to_finish; + int runtime_processing; + int num_dst_addrs; + dst_sockaddr_t dst_sockaddrs[MAX_DST_HOSTS]; uint8_t ttl; char *psk; switch_mutex_t *mutex; + switch_thread_rwlock_t *runtime_rwlock; switch_hash_t *peer_hash; - int loopback; + uint8_t loopback; + uint8_t loopback6; + char configuration_md5[SWITCH_MD5_DIGEST_STRING_SIZE]; } globals; struct peer_status { @@ -69,41 +99,70 @@ struct peer_status { time_t lastseen; }; -SWITCH_DECLARE_GLOBAL_STRING_FUNC(set_global_address, globals.address); +SWITCH_DECLARE_GLOBAL_STRING_FUNC(set_global_src_addr, globals.src_addr); +SWITCH_DECLARE_GLOBAL_STRING_FUNC(set_global_src_addr6, globals.src_addr6); +SWITCH_DECLARE_GLOBAL_STRING_FUNC(set_global_dst_addrs, globals.dst_addrs); SWITCH_DECLARE_GLOBAL_STRING_FUNC(set_global_bindings, globals.bindings); #ifdef HAVE_OPENSSL SWITCH_DECLARE_GLOBAL_STRING_FUNC(set_global_psk, globals.psk); #endif +#define CONF_FILE "event_multicast.conf" #define MULTICAST_EVENT "multicast::event" #define MULTICAST_PEERUP "multicast::peerup" #define MULTICAST_PEERDOWN "multicast::peerdown" -static switch_status_t load_config(void) + +static switch_xml_t open_config_file(const char *file_path, switch_xml_t *cfg, char *md5) { + char *configText; + switch_xml_t xml; + + if (!(xml = switch_xml_open_cfg(CONF_FILE, cfg, NULL))) { + switch_log_printf(SWITCH_CHANNEL_LOG, SWITCH_LOG_ERROR, "Open of %s failed\n", CONF_FILE); + } else if (*cfg) { + configText = switch_xml_toxml(*cfg, SWITCH_FALSE); + switch_md5_string(md5, configText, strlen(configText)); + switch_safe_free(configText); + } else { + switch_xml_free(xml); + xml = NULL; + } + + return xml; +} + +static switch_status_t load_config(switch_xml_t input_cfg) { switch_status_t status = SWITCH_STATUS_SUCCESS; - char *cf = "event_multicast.conf"; - switch_xml_t cfg, xml, settings, param; + switch_xml_t cfg, xml = NULL, settings, param; char *next, *cur; uint32_t count = 0; uint8_t custom = 0; - globals.ttl = 1; globals.key_count = 0; globals.loopback = 0; + globals.port = 0; + globals.num_dst_addrs = 0; - if (!(xml = switch_xml_open_cfg(cf, &cfg, NULL))) { - switch_log_printf(SWITCH_CHANNEL_LOG, SWITCH_LOG_ERROR, "Open of %s failed\n", cf); - return SWITCH_STATUS_TERM; + if (input_cfg) { + cfg = input_cfg; + } else { + if (!(xml = open_config_file(CONF_FILE, &cfg, globals.configuration_md5))) { + switch_log_printf(SWITCH_CHANNEL_LOG, SWITCH_LOG_ERROR, "Open of %s failed\n", CONF_FILE); + return SWITCH_STATUS_TERM; + } } - if ((settings = switch_xml_child(cfg, "settings"))) { for (param = switch_xml_child(settings, "param"); param; param = param->next) { char *var = (char *) switch_xml_attr_soft(param, "name"); char *val = (char *) switch_xml_attr_soft(param, "value"); if (!strcasecmp(var, "address")) { - set_global_address(val); + set_global_dst_addrs(switch_strip_whitespace(val)); + } else if (!strcasecmp(var, "source_address")) { + set_global_src_addr(switch_strip_whitespace(val)); + } else if (!strcasecmp(var, "source_address_ipv6")) { + set_global_src_addr6(switch_strip_whitespace(val)); } else if (!strcasecmp(var, "bindings")) { set_global_bindings(val); } else if (!strcasecmp(var, "port")) { @@ -124,7 +183,6 @@ static switch_status_t load_config(void) } else if (!strcasecmp(var, "loopback")) { globals.loopback = switch_true(val); } - } } @@ -161,12 +219,252 @@ static switch_status_t load_config(void) } } + if (zstr(globals.src_addr)) { + set_global_src_addr("0.0.0.0"); + } + + if (zstr(globals.src_addr6)) { + set_global_src_addr6("::"); + } + if (!globals.key_count) { - switch_log_printf(SWITCH_CHANNEL_LOG, SWITCH_LOG_NOTICE, "No Bindings\n"); + switch_log_printf(SWITCH_CHANNEL_LOG, SWITCH_LOG_NOTICE, "No Event Bindings\n"); } return status; +} +static void cleanup() +{ + /* Clean up sockets */ + if (globals.udp_socket) { + switch_socket_shutdown(globals.udp_socket, SWITCH_SHUTDOWN_READWRITE); + switch_socket_close(globals.udp_socket); + globals.udp_socket = NULL; + } + + if (globals.udp_socket6) { + switch_socket_shutdown(globals.udp_socket6, SWITCH_SHUTDOWN_READWRITE); + switch_socket_close(globals.udp_socket6); + globals.udp_socket6 = NULL; + } + + if (globals.event_hash) { + switch_core_hash_destroy(&globals.event_hash); + } + + if (globals.peer_hash) { + switch_core_hash_destroy(&globals.peer_hash); + } + + switch_safe_free(globals.src_addr); + switch_safe_free(globals.src_addr6); + switch_safe_free(globals.dst_addrs); + switch_safe_free(globals.bindings); + switch_safe_free(globals.psk); + + memset(globals.event_list, 0, SWITCH_EVENT_ALL + 1); +} + +static switch_status_t initialize_sockets(switch_xml_t input_cfg) +{ + switch_status_t status; + int i, dst_host_count = 0; + char *dst_hosts[MAX_DST_HOSTS] = { 0 }; + switch_sockaddr_t *local_ip_sockaddr; + switch_sockaddr_t *local_ip6_sockaddr; + + switch_core_hash_init(&globals.event_hash); + switch_core_hash_init(&globals.peer_hash); + + if (load_config(input_cfg) != SWITCH_STATUS_SUCCESS) { + switch_log_printf(SWITCH_CHANNEL_LOG, SWITCH_LOG_ERROR, "Cannot Configure\n"); + switch_goto_status(SWITCH_STATUS_TERM, fail); + } + + /* to attempt to avoid unicasting to ourself we need to know our IP address */ + switch_sockaddr_info_get(&local_ip_sockaddr, switch_core_get_variable("local_ip_v4"), SWITCH_INET, globals.port, 0, module_pool); + switch_sockaddr_info_get(&local_ip6_sockaddr, switch_core_get_variable("local_ip_v6"), SWITCH_INET6, globals.port, 0, module_pool); + + /* set up the destination sockaddrs */ + dst_host_count = switch_separate_string(globals.dst_addrs, ',', dst_hosts, MAX_DST_HOSTS); + for (i = 0; i < dst_host_count; i++) { + char *ip_addr_groups[8] = { 0 }; + char *host_string; + char ipv6_first_octet[3]; + + memset(&globals.dst_sockaddrs[globals.num_dst_addrs].sockaddr, 0, sizeof(dst_sockaddr_t)); + + if (globals.num_dst_addrs > MAX_DST_HOSTS) { + switch_log_printf(SWITCH_CHANNEL_LOG, SWITCH_LOG_ERROR, "Cannot add destination address: %s, exceeded maximum of %d\n", dst_hosts[i], MAX_DST_HOSTS); + continue; + } + + if (switch_sockaddr_info_get(&globals.dst_sockaddrs[globals.num_dst_addrs].sockaddr, dst_hosts[i], SWITCH_UNSPEC, globals.port, 0, module_pool) != SWITCH_STATUS_SUCCESS) { + switch_log_printf(SWITCH_CHANNEL_LOG, SWITCH_LOG_ERROR, "Cannot find address: %s\n", dst_hosts[i]); + switch_goto_status(SWITCH_STATUS_TERM, fail); + } + + /* best effort attempt to avoid unicasting to ourself */ + if (switch_cmp_addr(globals.dst_sockaddrs[globals.num_dst_addrs].sockaddr, local_ip_sockaddr, SWITCH_FALSE) || switch_cmp_addr(globals.dst_sockaddrs[globals.num_dst_addrs].sockaddr, local_ip6_sockaddr, SWITCH_FALSE)) { + /* this address is on this box, cancel the destination sockaddr setup and move on to the next address */ + switch_log_printf(SWITCH_CHANNEL_LOG, SWITCH_LOG_DEBUG, "Local IP, not adding as peer: %s\n", dst_hosts[i]); + globals.dst_sockaddrs[globals.num_dst_addrs].sockaddr = NULL; + globals.dst_sockaddrs[globals.num_dst_addrs].ipaddr = NULL; + continue; + } + + /* flag this address with the address type */ + host_string = strdup(dst_hosts[i]); + + if (switch_sockaddr_get_family(globals.dst_sockaddrs[globals.num_dst_addrs].sockaddr) == SWITCH_INET) { + globals.has_udp = 1; + switch_separate_string(host_string, '.', ip_addr_groups, sizeof(ip_addr_groups) / sizeof(ip_addr_groups[0])); + + /* IPv4 multicast addresses start with numbers between 224 & 239 inclusive */ + if (switch_safe_atoi(ip_addr_groups[0], 0) >= 224 && switch_safe_atoi(ip_addr_groups[0], 0) <= 239) { + globals.dst_sockaddrs[globals.num_dst_addrs].addrtype = IPV4_MULTICAST; + } else { + globals.dst_sockaddrs[globals.num_dst_addrs].addrtype = IPV4_UNICAST; + } + } else if (switch_sockaddr_get_family(globals.dst_sockaddrs[globals.num_dst_addrs].sockaddr) == SWITCH_INET6) { + globals.has_udp6 = 1; + switch_separate_string(host_string, ':', ip_addr_groups, 8); + + /* IPv6 multicast addresses have FF as the first octet */ + memcpy(ipv6_first_octet, ip_addr_groups[0], 2); + ipv6_first_octet[2] = '\0'; + if (strcasecmp(ipv6_first_octet, "FF") == 0) { + globals.dst_sockaddrs[globals.num_dst_addrs].addrtype = IPV6_MULTICAST; + } else { + globals.dst_sockaddrs[globals.num_dst_addrs].addrtype = IPV6_UNICAST; + } + } else { + globals.dst_sockaddrs[globals.num_dst_addrs].addrtype = IP_UNKOWN_TYPE; + switch_log_printf(SWITCH_CHANNEL_LOG, SWITCH_LOG_ERROR, "Unkown address family for peer: %s\n", dst_hosts[i]); + } + + /* store this address in our list of peers */ + switch_log_printf(SWITCH_CHANNEL_LOG, SWITCH_LOG_DEBUG, "Added %s peer: %s", addr_type_names[globals.dst_sockaddrs[globals.num_dst_addrs].addrtype], dst_hosts[i]); + globals.dst_sockaddrs[globals.num_dst_addrs].ipaddr = switch_core_strdup(module_pool, dst_hosts[i]); + globals.num_dst_addrs++; + switch_safe_free(host_string); + } + + /* create IPv4 source socket */ + if (globals.has_udp == 1) { + /* create IPv4 listen sockaddr*/ + if (switch_sockaddr_info_get(&globals.src_sockaddr, globals.src_addr, SWITCH_INET, globals.port, 0, module_pool) != SWITCH_STATUS_SUCCESS) { + switch_log_printf(SWITCH_CHANNEL_LOG, SWITCH_LOG_ERROR, "Cannot set IPv4 source address: %s\n", globals.src_addr); + switch_goto_status(SWITCH_STATUS_TERM, fail); + } + + /* create IPv4 socket */ + if (switch_socket_create(&globals.udp_socket, AF_INET, SOCK_DGRAM, 0, module_pool) != SWITCH_STATUS_SUCCESS) { + switch_log_printf(SWITCH_CHANNEL_LOG, SWITCH_LOG_ERROR, "Unable to create IPv4 Socket\n"); + switch_goto_status(SWITCH_STATUS_TERM, fail); + } + + if (switch_socket_opt_set(globals.udp_socket, SWITCH_SO_REUSEADDR, 1) != SWITCH_STATUS_SUCCESS) { + switch_log_printf(SWITCH_CHANNEL_LOG, SWITCH_LOG_ERROR, "IPv4 unable to resue socket\n"); + switch_goto_status(SWITCH_STATUS_TERM, fail); + } + + if (switch_socket_opt_set(globals.udp_socket, SWITCH_SO_NONBLOCK, TRUE) != SWITCH_STATUS_SUCCESS) { + switch_log_printf(SWITCH_CHANNEL_LOG, SWITCH_LOG_ERROR, "IPv4 unable to set nonblocking mode on socket\n"); + switch_goto_status(SWITCH_STATUS_TERM, fail); + } + + /* no harm in doing this even without multicast destinations */ + if (switch_mcast_hops(globals.udp_socket, globals.ttl) != SWITCH_STATUS_SUCCESS) { + switch_log_printf(SWITCH_CHANNEL_LOG, SWITCH_LOG_ERROR, "Failed to set IPv4 multicast ttl to '%d'\n", globals.ttl); + switch_goto_status(SWITCH_STATUS_TERM, fail); + } + + if (switch_mcast_loopback(globals.udp_socket, globals.loopback) != SWITCH_STATUS_SUCCESS) { + switch_log_printf(SWITCH_CHANNEL_LOG, SWITCH_LOG_ERROR, "Failed to set IPv4 multicast loopback to '%d'\n", globals.loopback); + switch_goto_status(SWITCH_STATUS_TERM, fail); + } + /* start listening on this IPv4 socket */ + if (switch_socket_bind(globals.udp_socket, globals.src_sockaddr) != SWITCH_STATUS_SUCCESS) { + switch_log_printf(SWITCH_CHANNEL_LOG, SWITCH_LOG_ERROR, "Unable to bind IPv4 Socket\n"); + switch_goto_status(SWITCH_STATUS_TERM, fail); + } else { + switch_log_printf(SWITCH_CHANNEL_LOG, SWITCH_LOG_DEBUG, "IPv4 source set to: %s\n", globals.src_addr); + } + } + + /* create IPv6 source socket */ + if (globals.has_udp6 == 1) { + /* create IPv6 listen sockaddr */ + if (switch_sockaddr_info_get(&globals.src_sockaddr6, globals.src_addr6, SWITCH_INET6, globals.port, 0, module_pool) != SWITCH_STATUS_SUCCESS) { + switch_log_printf(SWITCH_CHANNEL_LOG, SWITCH_LOG_ERROR, "Cannot set IPv6 source address: %s\n", globals.src_addr6); + switch_goto_status(SWITCH_STATUS_TERM, fail); + } + + /* create IPv6 socket */ + if (switch_socket_create(&globals.udp_socket6, AF_INET6, SOCK_DGRAM, 0, module_pool) != SWITCH_STATUS_SUCCESS) { + switch_log_printf(SWITCH_CHANNEL_LOG, SWITCH_LOG_ERROR, "Unable to create IPv6 Socket\n"); + switch_goto_status(SWITCH_STATUS_TERM, fail); + } + + if (switch_socket_opt_set(globals.udp_socket6, SWITCH_SO_REUSEADDR, 1) != SWITCH_STATUS_SUCCESS) { + switch_log_printf(SWITCH_CHANNEL_LOG, SWITCH_LOG_ERROR, "IPv6 unable to reuse socket\n"); + switch_goto_status(SWITCH_STATUS_TERM, fail); + } + + if (switch_socket_opt_set(globals.udp_socket6, SWITCH_SO_NONBLOCK, TRUE) != SWITCH_STATUS_SUCCESS) { + switch_log_printf(SWITCH_CHANNEL_LOG, SWITCH_LOG_ERROR, "IPv6 unable to set nonblocking mode on socket\n"); + switch_goto_status(SWITCH_STATUS_TERM, fail); + } + + /* no harm in doing this even without multicast destinations */ + /* Bug in APR < v1.2.13, cannot set TTL on IPv6 multicast sockets */ + /* + if (switch_mcast_hops(globals.udp_socket6, globals.ttl) != SWITCH_STATUS_SUCCESS) { + switch_log_printf(SWITCH_CHANNEL_LOG, SWITCH_LOG_ERROR, "Failed to set IPv6 multicast ttl to '%d'\n", globals.ttl); + switch_goto_status(SWITCH_STATUS_TERM, fail); + } + */ + + if (switch_mcast_loopback(globals.udp_socket6, globals.loopback6) != SWITCH_STATUS_SUCCESS) { + switch_log_printf(SWITCH_CHANNEL_LOG, SWITCH_LOG_ERROR, "Failed to set IPv6 multicast loopback to '%d'\n", globals.loopback6); + switch_goto_status(SWITCH_STATUS_TERM, fail); + } + + /* start listening on this IPv6 socket */ + if (switch_socket_bind(globals.udp_socket6, globals.src_sockaddr6) != SWITCH_STATUS_SUCCESS) { + switch_log_printf(SWITCH_CHANNEL_LOG, SWITCH_LOG_ERROR, "Unable to bind IPv6 Socket\n"); + switch_goto_status(SWITCH_STATUS_TERM, fail); + } else { + switch_log_printf(SWITCH_CHANNEL_LOG, SWITCH_LOG_DEBUG, "IPv6 source set to: %s\n", globals.src_addr6); + } + } + + /* join multicast destinations */ + for (i = 0; i < globals.num_dst_addrs; i++) { + if (globals.dst_sockaddrs[i].addrtype == IPV4_MULTICAST) { + if (switch_mcast_join(globals.udp_socket, globals.dst_sockaddrs[i].sockaddr, NULL, NULL) != SWITCH_STATUS_SUCCESS) { + switch_log_printf(SWITCH_CHANNEL_LOG, SWITCH_LOG_ERROR, "Multicast Error\n"); + switch_goto_status(SWITCH_STATUS_TERM, fail); + } + } + + if (globals.dst_sockaddrs[i].addrtype == IPV6_MULTICAST) { + if (switch_mcast_join(globals.udp_socket6, globals.dst_sockaddrs[i].sockaddr, NULL, NULL) != SWITCH_STATUS_SUCCESS) { + switch_log_printf(SWITCH_CHANNEL_LOG, SWITCH_LOG_ERROR, "Multicast Error\n"); + switch_goto_status(SWITCH_STATUS_TERM, fail); + } + } + } + + /* indicate that the module should continue to be loaded */ + return SWITCH_STATUS_SUCCESS; + +fail: + cleanup(); + + return status; } static void event_handler(switch_event_t *event) @@ -178,10 +476,10 @@ static void event_handler(switch_event_t *event) } if (event->subclass_name && (!strcmp(event->subclass_name, MULTICAST_EVENT) || - !strcmp(event->subclass_name, MULTICAST_PEERUP) || !strcmp(event->subclass_name, MULTICAST_PEERDOWN))) { + !strcmp(event->subclass_name, MULTICAST_PEERUP) || !strcmp(event->subclass_name, MULTICAST_PEERDOWN))) { char *event_name, *sender; if ((event_name = switch_event_get_header(event, "orig-event-name")) && - !strcasecmp(event_name, "HEARTBEAT") && (sender = switch_event_get_header(event, "orig-multicast-sender"))) { + !strcasecmp(event_name, "HEARTBEAT") && (sender = switch_event_get_header(event, "orig-multicast-sender"))) { struct peer_status *p; time_t now = switch_epoch_time_now(NULL); @@ -221,21 +519,42 @@ static void event_handler(switch_event_t *event) } if (event->event_id == SWITCH_EVENT_RELOADXML) { + switch_bool_t config_changed = SWITCH_FALSE; + char tempMD5[SWITCH_MD5_DIGEST_STRING_SIZE]; + switch_xml_t xml, cfg; + + if (!(xml = open_config_file(CONF_FILE, &cfg, tempMD5))) { + switch_log_printf(SWITCH_CHANNEL_LOG, SWITCH_LOG_ERROR, "Open of %s failed\n", CONF_FILE); + return; + } + switch_mutex_lock(globals.mutex); - switch_core_hash_destroy(&globals.event_hash); - globals.event_hash = NULL; - if (globals.psk) { - switch_safe_free(globals.psk); - globals.psk = NULL; - } - switch_core_hash_init(&globals.event_hash); - memset(globals.event_list, 0, SWITCH_EVENT_ALL + 1); - if (load_config() != SWITCH_STATUS_SUCCESS) { - switch_log_printf(SWITCH_CHANNEL_LOG, SWITCH_LOG_WARNING, "Failed to reload config file\n"); - } else { - switch_log_printf(SWITCH_CHANNEL_LOG, SWITCH_LOG_INFO, "Event Multicast Reloaded\n"); + + config_changed = strcmp(globals.configuration_md5, tempMD5) ? SWITCH_TRUE : SWITCH_FALSE; + /* If the config has changed, reload the configuration */ + if (config_changed) { + switch_log_printf(SWITCH_CHANNEL_LOG, SWITCH_LOG_INFO, "Configuration changed, reloading\n"); + switch_thread_rwlock_wrlock(globals.runtime_rwlock); + + cleanup(); + + /* Re-initialize the module */ + if (initialize_sockets(cfg) != SWITCH_STATUS_SUCCESS) { + globals.runtime_processing = 0; + switch_log_printf(SWITCH_CHANNEL_LOG, SWITCH_LOG_WARNING, "Unable to reinitialize sockets.\n"); + /* Invalidate current configuration md5 */ + switch_md5_string(globals.configuration_md5, "", strlen("")); + } else { + switch_md5_string(globals.configuration_md5, tempMD5, strlen(tempMD5)); + globals.runtime_processing = 1; + switch_log_printf(SWITCH_CHANNEL_LOG, SWITCH_LOG_INFO, "Reloaded\n"); + } + + switch_thread_rwlock_unlock(globals.runtime_rwlock); } + switch_mutex_unlock(globals.mutex); + switch_xml_free(xml); } if (event->event_id == SWITCH_EVENT_HEARTBEAT) { @@ -282,83 +601,199 @@ static void event_handler(switch_event_t *event) char *packet; switch (event->event_id) { - case SWITCH_EVENT_LOG: - return; - default: - switch_event_add_header_string(event, SWITCH_STACK_BOTTOM, "Multicast-Sender", switch_core_get_switchname()); - if (switch_event_serialize(event, &packet, SWITCH_TRUE) == SWITCH_STATUS_SUCCESS) { - size_t len; - char *buf; + case SWITCH_EVENT_LOG: + return; + default: + switch_event_add_header_string(event, SWITCH_STACK_BOTTOM, "Multicast-Sender", switch_core_get_switchname()); + if (switch_event_serialize(event, &packet, SWITCH_TRUE) == SWITCH_STATUS_SUCCESS) { + size_t len; + char *buf; + int i; + #ifdef HAVE_OPENSSL - int outlen, tmplen; + int outlen, tmplen; #if OPENSSL_VERSION_NUMBER >= 0x10100000 - EVP_CIPHER_CTX *ctx; + EVP_CIPHER_CTX *ctx; #else - EVP_CIPHER_CTX ctx; + EVP_CIPHER_CTX ctx; #endif - char uuid_str[SWITCH_UUID_FORMATTED_LENGTH + 1]; - switch_uuid_t uuid; + char uuid_str[SWITCH_UUID_FORMATTED_LENGTH + 1]; + switch_uuid_t uuid; - switch_uuid_get(&uuid); - switch_uuid_format(uuid_str, &uuid); - len = strlen(packet) + SWITCH_UUID_FORMATTED_LENGTH + EVP_MAX_IV_LENGTH + strlen((char *) MAGIC); + switch_uuid_get(&uuid); + switch_uuid_format(uuid_str, &uuid); + len = strlen(packet) + SWITCH_UUID_FORMATTED_LENGTH + EVP_MAX_IV_LENGTH + strlen((char *) MAGIC); #else - len = strlen(packet) + strlen((char *) MAGIC); + len = strlen(packet) + strlen((char *) MAGIC); #endif - buf = malloc(len + 1); - memset(buf, 0, len + 1); - switch_assert(buf); + buf = malloc(len + 1); + memset(buf, 0, len + 1); + switch_assert(buf); #ifdef HAVE_OPENSSL - if (globals.psk) { - switch_copy_string(buf, uuid_str, SWITCH_UUID_FORMATTED_LENGTH); + if (globals.psk) { + switch_copy_string(buf, uuid_str, SWITCH_UUID_FORMATTED_LENGTH); #if OPENSSL_VERSION_NUMBER >= 0x10100000 - ctx = EVP_CIPHER_CTX_new(); - EVP_EncryptInit(ctx, EVP_bf_cbc(), NULL, NULL); - EVP_CIPHER_CTX_set_key_length(ctx, strlen(globals.psk)); - EVP_EncryptInit(ctx, NULL, (unsigned char *) globals.psk, (unsigned char *) uuid_str); - EVP_EncryptUpdate(ctx, (unsigned char *) buf + SWITCH_UUID_FORMATTED_LENGTH, - &outlen, (unsigned char *) packet, (int) strlen(packet)); - EVP_EncryptUpdate(ctx, (unsigned char *) buf + SWITCH_UUID_FORMATTED_LENGTH + outlen, - &tmplen, (unsigned char *) MAGIC, (int) strlen((char *) MAGIC)); - outlen += tmplen; - EVP_EncryptFinal(ctx, (unsigned char *) buf + SWITCH_UUID_FORMATTED_LENGTH + outlen, &tmplen); - EVP_CIPHER_CTX_free(ctx); + ctx = EVP_CIPHER_CTX_new(); + EVP_EncryptInit(ctx, EVP_bf_cbc(), NULL, NULL); + EVP_CIPHER_CTX_set_key_length(ctx, strlen(globals.psk)); + EVP_EncryptInit(ctx, NULL, (unsigned char *) globals.psk, (unsigned char *) uuid_str); + EVP_EncryptUpdate(ctx, (unsigned char *) buf + SWITCH_UUID_FORMATTED_LENGTH, + &outlen, (unsigned char *) packet, (int) strlen(packet)); + EVP_EncryptUpdate(ctx, (unsigned char *) buf + SWITCH_UUID_FORMATTED_LENGTH + outlen, + &tmplen, (unsigned char *) MAGIC, (int) strlen((char *) MAGIC)); + outlen += tmplen; + EVP_EncryptFinal(ctx, (unsigned char *) buf + SWITCH_UUID_FORMATTED_LENGTH + outlen, &tmplen); + EVP_CIPHER_CTX_free(ctx); #else - EVP_CIPHER_CTX_init(&ctx); - EVP_EncryptInit(&ctx, EVP_bf_cbc(), NULL, NULL); - EVP_CIPHER_CTX_set_key_length(&ctx, strlen(globals.psk)); - EVP_EncryptInit(&ctx, NULL, (unsigned char *) globals.psk, (unsigned char *) uuid_str); - EVP_EncryptUpdate(&ctx, (unsigned char *) buf + SWITCH_UUID_FORMATTED_LENGTH, - &outlen, (unsigned char *) packet, (int) strlen(packet)); - EVP_EncryptUpdate(&ctx, (unsigned char *) buf + SWITCH_UUID_FORMATTED_LENGTH + outlen, - &tmplen, (unsigned char *) MAGIC, (int) strlen((char *) MAGIC)); - outlen += tmplen; - EVP_EncryptFinal(&ctx, (unsigned char *) buf + SWITCH_UUID_FORMATTED_LENGTH + outlen, &tmplen); - EVP_CIPHER_CTX_cleanup(&ctx); + EVP_CIPHER_CTX_init(&ctx); + EVP_EncryptInit(&ctx, EVP_bf_cbc(), NULL, NULL); + EVP_CIPHER_CTX_set_key_length(&ctx, strlen(globals.psk)); + EVP_EncryptInit(&ctx, NULL, (unsigned char *) globals.psk, (unsigned char *) uuid_str); + EVP_EncryptUpdate(&ctx, (unsigned char *) buf + SWITCH_UUID_FORMATTED_LENGTH, + &outlen, (unsigned char *) packet, (int) strlen(packet)); + EVP_EncryptUpdate(&ctx, (unsigned char *) buf + SWITCH_UUID_FORMATTED_LENGTH + outlen, + &tmplen, (unsigned char *) MAGIC, (int) strlen((char *) MAGIC)); + outlen += tmplen; + EVP_EncryptFinal(&ctx, (unsigned char *) buf + SWITCH_UUID_FORMATTED_LENGTH + outlen, &tmplen); + EVP_CIPHER_CTX_cleanup(&ctx); #endif - outlen += tmplen; - len = (size_t) outlen + SWITCH_UUID_FORMATTED_LENGTH; - *(buf + SWITCH_UUID_FORMATTED_LENGTH + outlen) = '\0'; - } else { + outlen += tmplen; + len = (size_t) outlen + SWITCH_UUID_FORMATTED_LENGTH; + *(buf + SWITCH_UUID_FORMATTED_LENGTH + outlen) = '\0'; + } else { #endif - switch_copy_string(buf, packet, len); - switch_copy_string(buf + strlen(packet), (char *) MAGIC, strlen((char *) MAGIC) + 1); + switch_copy_string(buf, packet, len); + switch_copy_string(buf + strlen(packet), (char *) MAGIC, strlen((char *) MAGIC) + 1); #ifdef HAVE_OPENSSL + } +#endif + + for (i = 0; i < globals.num_dst_addrs; i++) { + /* Send to IPv4 */ + if (globals.dst_sockaddrs[i].addrtype == IPV4_UNICAST || globals.dst_sockaddrs[i].addrtype == IPV4_MULTICAST) { + switch_socket_sendto(globals.udp_socket, globals.dst_sockaddrs[i].sockaddr, 0, buf, &len); + } + + /* Send to IPv4 */ + if (globals.dst_sockaddrs[i].addrtype == IPV6_UNICAST || globals.dst_sockaddrs[i].addrtype == IPV6_MULTICAST) { + switch_log_printf(SWITCH_CHANNEL_LOG, SWITCH_LOG_DEBUG, "Sending message to IPv6: %s\n", globals.dst_sockaddrs[i].ipaddr); + switch_socket_sendto(globals.udp_socket6, globals.dst_sockaddrs[i].sockaddr, 0, buf, &len); + } + } + + switch_safe_free(packet); + switch_safe_free(buf); } -#endif - - switch_socket_sendto(globals.udp_socket, globals.addr, 0, buf, &len); - switch_safe_free(packet); - switch_safe_free(buf); - } - break; + break; } } return; } +static switch_status_t process_packet(char* packet, size_t len) +{ + char *m; + switch_event_t *local_event; + +#ifdef HAVE_OPENSSL + if (globals.psk) { + char uuid_str[SWITCH_UUID_FORMATTED_LENGTH + 1]; + char *tmp; + int outl, tmplen; +#if OPENSSL_VERSION_NUMBER >= 0x10100000L + EVP_CIPHER_CTX *ctx; +#else + EVP_CIPHER_CTX ctx; +#endif + + len -= SWITCH_UUID_FORMATTED_LENGTH; + + tmp = malloc(len); + + memset(tmp, 0, len); + + switch_copy_string(uuid_str, packet, SWITCH_UUID_FORMATTED_LENGTH); + packet += SWITCH_UUID_FORMATTED_LENGTH; + +#if OPENSSL_VERSION_NUMBER >= 0x10100000L + ctx = EVP_CIPHER_CTX_new(); + EVP_DecryptInit(ctx, EVP_bf_cbc(), NULL, NULL); + EVP_CIPHER_CTX_set_key_length(ctx, strlen(globals.psk)); + EVP_DecryptInit(ctx, NULL, (unsigned char *)globals.psk, (unsigned char *)uuid_str); + EVP_DecryptUpdate(ctx, (unsigned char *)tmp, &outl, (unsigned char *)packet, (int)len); + EVP_DecryptFinal(ctx, (unsigned char *)tmp + outl, &tmplen); + EVP_CIPHER_CTX_free(ctx); +#else + EVP_CIPHER_CTX_init(&ctx); + EVP_DecryptInit(&ctx, EVP_bf_cbc(), NULL, NULL); + EVP_CIPHER_CTX_set_key_length(&ctx, strlen(globals.psk)); + EVP_DecryptInit(&ctx, NULL, (unsigned char *)globals.psk, (unsigned char *)uuid_str); + EVP_DecryptUpdate(&ctx, (unsigned char *)tmp, &outl, (unsigned char *)packet, (int)len); + EVP_DecryptFinal(&ctx, (unsigned char *)tmp + outl, &tmplen); + EVP_CIPHER_CTX_cleanup(&ctx); +#endif + + *(tmp + outl + tmplen) = '\0'; + + /*switch_log_printf(SWITCH_CHANNEL_LOG, SWITCH_LOG_DEBUG, "decrypted event as %s\n----------\n of actual length %d (%d) %d\n", tmp, outl + tmplen, (int) len, (int) strlen(tmp)); */ + packet = tmp; + + } +#endif + + if ((m = strchr(packet, (int)MAGIC[0])) != 0) { + /*switch_log_printf(SWITCH_CHANNEL_LOG, SWITCH_LOG_DEBUG, "Found start of magic string\n"); */ + if (!strncmp((char *)MAGIC, m, strlen((char *)MAGIC))) { + /*switch_log_printf(SWITCH_CHANNEL_LOG, SWITCH_LOG_DEBUG, "Found entire magic string\n"); */ + *m = '\0'; + } else { + switch_log_printf(SWITCH_CHANNEL_LOG, SWITCH_LOG_ERROR, "Inbound event packet is missing the complete validation string.\n"); + return SWITCH_STATUS_NOOP; + } + } else { + switch_log_printf(SWITCH_CHANNEL_LOG, SWITCH_LOG_WARNING, "Failed to validate inbound event packet, is your PSK correctly configured?\n"); + return SWITCH_STATUS_NOOP; + } + + /*switch_log_printf(SWITCH_CHANNEL_LOG, SWITCH_LOG_DEBUG, "\nEVENT %d\n--------------------------------\n%s\n", (int) len, packet); */ + if (switch_event_create_subclass(&local_event, SWITCH_EVENT_CUSTOM, MULTICAST_EVENT) == SWITCH_STATUS_SUCCESS) { + char *var, *val, *term = NULL, tmpname[128]; + switch_event_add_header_string(local_event, SWITCH_STACK_BOTTOM, "Multicast", "yes"); + var = packet; + while (var && *var) { + if ((val = strchr(var, ':')) != 0) { + *val++ = '\0'; + while (*val == ' ') { + val++; + } + if ((term = strchr(val, '\r')) != 0 || (term = strchr(val, '\n')) != 0) { + *term = '\0'; + while (*term == '\r' || *term == '\n') { + term++; + } + } + switch_url_decode(val); + switch_snprintf(tmpname, sizeof(tmpname), "Orig-%s", var); + switch_event_add_header_string(local_event, SWITCH_STACK_BOTTOM, tmpname, val); + var = term + 1; + } else { + /* This should be our magic packet, done processing incoming headers */ + break; + } + } + + if (var && strlen(var) > 1) { + switch_event_add_body(local_event, "%s", var); + } + + return switch_event_fire(&local_event); + } + + return SWITCH_STATUS_NOOP; +} + SWITCH_STANDARD_API(multicast_peers) { switch_hash_index_t *cur; @@ -368,8 +803,26 @@ SWITCH_STANDARD_API(multicast_peers) time_t now = switch_epoch_time_now(NULL); struct peer_status *last; char *host; - int i = 0; + int i; + switch_mutex_lock(globals.mutex); + + /* Output current module state */ + stream->write_function(stream, "Module state: "); + if (globals.running == 1 && globals.runtime_processing == 1) { + stream->write_function(stream, "Active\n\n"); + } else { + stream->write_function(stream, "Inactive\n\n"); + } + + stream->write_function(stream, "Configured peers:\n"); + for (i = 0; i < globals.num_dst_addrs; i++) { + stream->write_function(stream, "\t%s: %s\n", addr_type_names[globals.dst_sockaddrs[i].addrtype], globals.dst_sockaddrs[i].ipaddr); + } + + stream->write_function(stream, "\n\n"); + + i = 0; for (cur = switch_core_hash_first(globals.peer_hash); cur; cur = switch_core_hash_next(&cur)) { switch_core_hash_this(cur, &key, &keylen, &value); host = (char *) key; @@ -383,6 +836,8 @@ SWITCH_STANDARD_API(multicast_peers) stream->write_function(stream, "No multicast peers seen\n"); } + switch_mutex_unlock(globals.mutex); + return SWITCH_STATUS_SUCCESS; } @@ -396,51 +851,14 @@ SWITCH_MODULE_LOAD_FUNCTION(mod_event_multicast_load) switch_mutex_init(&globals.mutex, SWITCH_MUTEX_NESTED, pool); module_pool = pool; - switch_core_hash_init(&globals.event_hash); - switch_core_hash_init(&globals.peer_hash); + switch_thread_rwlock_create(&globals.runtime_rwlock, pool); - globals.key_count = 0; - - if (load_config() != SWITCH_STATUS_SUCCESS) { - switch_log_printf(SWITCH_CHANNEL_LOG, SWITCH_LOG_ERROR, "Cannot Configure\n"); - switch_goto_status(SWITCH_STATUS_TERM, fail); - } - - if (switch_sockaddr_info_get(&globals.addr, globals.address, SWITCH_UNSPEC, globals.port, 0, module_pool) != SWITCH_STATUS_SUCCESS) { - switch_log_printf(SWITCH_CHANNEL_LOG, SWITCH_LOG_ERROR, "Cannot find address\n"); - switch_goto_status(SWITCH_STATUS_TERM, fail); - } - - if (switch_socket_create(&globals.udp_socket, AF_INET, SOCK_DGRAM, 0, module_pool) != SWITCH_STATUS_SUCCESS) { - switch_log_printf(SWITCH_CHANNEL_LOG, SWITCH_LOG_ERROR, "Socket Error\n"); - switch_goto_status(SWITCH_STATUS_TERM, fail); - } - - if (switch_socket_opt_set(globals.udp_socket, SWITCH_SO_REUSEADDR, 1) != SWITCH_STATUS_SUCCESS) { - switch_log_printf(SWITCH_CHANNEL_LOG, SWITCH_LOG_ERROR, "Socket Option Error\n"); - switch_goto_status(SWITCH_STATUS_TERM, fail); - } - - if (switch_mcast_join(globals.udp_socket, globals.addr, NULL, NULL) != SWITCH_STATUS_SUCCESS) { - switch_log_printf(SWITCH_CHANNEL_LOG, SWITCH_LOG_ERROR, "Multicast Error\n"); - switch_goto_status(SWITCH_STATUS_TERM, fail); - } - - if (switch_mcast_hops(globals.udp_socket, globals.ttl) != SWITCH_STATUS_SUCCESS) { - switch_log_printf(SWITCH_CHANNEL_LOG, SWITCH_LOG_ERROR, "Failed to set ttl to '%d'\n", globals.ttl); - switch_goto_status(SWITCH_STATUS_TERM, fail); - } - - if (switch_mcast_loopback(globals.udp_socket, (uint8_t)globals.loopback) != SWITCH_STATUS_SUCCESS) { - switch_log_printf(SWITCH_CHANNEL_LOG, SWITCH_LOG_ERROR, "Failed to set loopback to '%d'\n", globals.loopback); - switch_goto_status(SWITCH_STATUS_TERM, fail); - } - - if (switch_socket_bind(globals.udp_socket, globals.addr) != SWITCH_STATUS_SUCCESS) { - switch_log_printf(SWITCH_CHANNEL_LOG, SWITCH_LOG_ERROR, "Bind Error\n"); - switch_goto_status(SWITCH_STATUS_TERM, fail); + if (initialize_sockets(NULL) != SWITCH_STATUS_SUCCESS) { + switch_log_printf(SWITCH_CHANNEL_LOG, SWITCH_LOG_ERROR, "Unable to initialize sockets."); + switch_goto_status(SWITCH_STATUS_GENERR, fail); } + /* Reserve the module specific events */ if (switch_event_reserve_subclass(MULTICAST_EVENT) != SWITCH_STATUS_SUCCESS) { switch_log_printf(SWITCH_CHANNEL_LOG, SWITCH_LOG_ERROR, "Couldn't register subclass %s!\n", MULTICAST_EVENT); switch_goto_status(SWITCH_STATUS_GENERR, fail); @@ -456,13 +874,11 @@ SWITCH_MODULE_LOAD_FUNCTION(mod_event_multicast_load) switch_goto_status(SWITCH_STATUS_GENERR, fail); } + /* Bind to the event bus */ if (switch_event_bind(modname, SWITCH_EVENT_ALL, SWITCH_EVENT_SUBCLASS_ANY, event_handler, NULL) != SWITCH_STATUS_SUCCESS) { - switch_log_printf(SWITCH_CHANNEL_LOG, SWITCH_LOG_ERROR, "Couldn't bind!\n"); + switch_log_printf(SWITCH_CHANNEL_LOG, SWITCH_LOG_ERROR, "Couldn't bind to event bus!\n"); switch_goto_status(SWITCH_STATUS_GENERR, fail); } -#ifdef USE_NONBLOCK - switch_socket_opt_set(globals.udp_socket, SWITCH_SO_NONBLOCK, TRUE); -#endif /* connect my internal structure to the blank pointer passed to me */ *module_interface = switch_loadable_module_create_module_interface(pool, modname); @@ -473,44 +889,33 @@ SWITCH_MODULE_LOAD_FUNCTION(mod_event_multicast_load) return SWITCH_STATUS_SUCCESS; - fail: - - if (globals.udp_socket) { - switch_socket_close(globals.udp_socket); - } +fail: switch_event_free_subclass(MULTICAST_EVENT); switch_event_free_subclass(MULTICAST_PEERUP); switch_event_free_subclass(MULTICAST_PEERDOWN); return status; - } - SWITCH_MODULE_SHUTDOWN_FUNCTION(mod_event_multicast_shutdown) { globals.running = 0; switch_event_unbind_callback(event_handler); - switch_mutex_lock(globals.mutex); - if (globals.udp_socket) { - switch_socket_shutdown(globals.udp_socket, 2); + while (globals.runtime_thread_has_to_finish) { + switch_yield(100 * 1000); } + switch_mutex_lock(globals.mutex); + switch_event_free_subclass(MULTICAST_EVENT); switch_event_free_subclass(MULTICAST_PEERUP); switch_event_free_subclass(MULTICAST_PEERDOWN); - if (globals.event_hash) { - switch_core_hash_destroy(&globals.event_hash); - } - if (globals.peer_hash) { - switch_core_hash_destroy(&globals.peer_hash); - } + cleanup(); - switch_safe_free(globals.address); - switch_safe_free(globals.bindings); + switch_thread_rwlock_destroy(globals.runtime_rwlock); switch_mutex_unlock(globals.mutex); return SWITCH_STATUS_SUCCESS; @@ -518,141 +923,77 @@ SWITCH_MODULE_SHUTDOWN_FUNCTION(mod_event_multicast_shutdown) SWITCH_MODULE_RUNTIME_FUNCTION(mod_event_multicast_runtime) { - switch_event_t *local_event; - char *buf, *m; - switch_sockaddr_t *addr; + char *buf; + + globals.runtime_thread_has_to_finish = 1; buf = (char *) malloc(MULTICAST_BUFFSIZE); switch_assert(buf); - switch_sockaddr_info_get(&addr, NULL, SWITCH_UNSPEC, 0, 0, module_pool); globals.running = 1; + globals.runtime_processing = 1; while (globals.running == 1) { - char *myaddr; + int rxdata = 0; size_t len = MULTICAST_BUFFSIZE - 1; - char *packet; switch_status_t status; - memset(buf, 0, len + 1); - switch_sockaddr_ip_get(&myaddr, globals.addr); - if ((status = switch_socket_recvfrom(addr, globals.udp_socket, 0, buf, &len)) != SWITCH_STATUS_SUCCESS || !len || !globals.running) { + switch_thread_rwlock_rdlock(globals.runtime_rwlock); + + if (globals.running != 1) { + switch_thread_rwlock_unlock(globals.runtime_rwlock); break; - } -#ifdef USE_NONBLOCK - if (!len) { - if (SWITCH_STATUS_IS_BREAK(status)) { - switch_yield(100000); - continue; - } - - break; - } -#endif - - packet = buf; - -#ifdef HAVE_OPENSSL - if (globals.psk) { - char uuid_str[SWITCH_UUID_FORMATTED_LENGTH + 1]; - char *tmp; - int outl, tmplen; -#if OPENSSL_VERSION_NUMBER >= 0x10100000L - EVP_CIPHER_CTX *ctx; -#else - EVP_CIPHER_CTX ctx; -#endif - - len -= SWITCH_UUID_FORMATTED_LENGTH; - - tmp = malloc(len); - - memset(tmp, 0, len); - - switch_copy_string(uuid_str, packet, SWITCH_UUID_FORMATTED_LENGTH); - packet += SWITCH_UUID_FORMATTED_LENGTH; - -#if OPENSSL_VERSION_NUMBER >= 0x10100000L - ctx = EVP_CIPHER_CTX_new(); - EVP_DecryptInit(ctx, EVP_bf_cbc(), NULL, NULL); - EVP_CIPHER_CTX_set_key_length(ctx, strlen(globals.psk)); - EVP_DecryptInit(ctx, NULL, (unsigned char *) globals.psk, (unsigned char *) uuid_str); - EVP_DecryptUpdate(ctx, (unsigned char *) tmp, &outl, (unsigned char *) packet, (int) len); - EVP_DecryptFinal(ctx, (unsigned char *) tmp + outl, &tmplen); - EVP_CIPHER_CTX_free(ctx); -#else - EVP_CIPHER_CTX_init(&ctx); - EVP_DecryptInit(&ctx, EVP_bf_cbc(), NULL, NULL); - EVP_CIPHER_CTX_set_key_length(&ctx, strlen(globals.psk)); - EVP_DecryptInit(&ctx, NULL, (unsigned char *) globals.psk, (unsigned char *) uuid_str); - EVP_DecryptUpdate(&ctx, (unsigned char *) tmp, &outl, (unsigned char *) packet, (int) len); - EVP_DecryptFinal(&ctx, (unsigned char *) tmp + outl, &tmplen); - EVP_CIPHER_CTX_cleanup(&ctx); -#endif - - *(tmp + outl + tmplen) = '\0'; - - /*switch_log_printf(SWITCH_CHANNEL_LOG, SWITCH_LOG_DEBUG, "decrypted event as %s\n----------\n of actual length %d (%d) %d\n", tmp, outl + tmplen, (int) len, (int) strlen(tmp)); */ - packet = tmp; - - } -#endif - if ((m = strchr(packet, (int) MAGIC[0])) != 0) { - /*switch_log_printf(SWITCH_CHANNEL_LOG, SWITCH_LOG_DEBUG, "Found start of magic string\n"); */ - if (!strncmp((char *) MAGIC, m, strlen((char *) MAGIC))) { - /*switch_log_printf(SWITCH_CHANNEL_LOG, SWITCH_LOG_DEBUG, "Found entire magic string\n"); */ - *m = '\0'; - } else { - switch_log_printf(SWITCH_CHANNEL_LOG, SWITCH_LOG_DEBUG, "Failed to find entire magic string\n"); - continue; - } - } else { - switch_log_printf(SWITCH_CHANNEL_LOG, SWITCH_LOG_WARNING, "Failed to find start of magic string\n"); + } else if (globals.runtime_processing != 1) { + switch_thread_rwlock_unlock(globals.runtime_rwlock); + switch_yield(100 * 1000); continue; } - /*switch_log_printf(SWITCH_CHANNEL_LOG, SWITCH_LOG_DEBUG, "\nEVENT %d\n--------------------------------\n%s\n", (int) len, packet); */ - if (switch_event_create_subclass(&local_event, SWITCH_EVENT_CUSTOM, MULTICAST_EVENT) == SWITCH_STATUS_SUCCESS) { - char *var, *val, *term = NULL, tmpname[128]; - switch_event_add_header_string(local_event, SWITCH_STACK_BOTTOM, "Multicast", "yes"); - var = packet; - while (var && *var) { - if ((val = strchr(var, ':')) != 0) { - *val++ = '\0'; - while (*val == ' ') { - val++; - } - if ((term = strchr(val, '\r')) != 0 || (term = strchr(val, '\n')) != 0) { - *term = '\0'; - while (*term == '\r' || *term == '\n') { - term++; - } - } - switch_url_decode(val); - switch_snprintf(tmpname, sizeof(tmpname), "Orig-%s", var); - switch_event_add_header_string(local_event, SWITCH_STACK_BOTTOM, tmpname, val); - var = term + 1; - } else { - break; - } + memset(buf, 0, len + 1); + + /* If there's data in the IPv4 packet, process it */ + if (globals.has_udp == 1) { + status = switch_socket_recv(globals.udp_socket, buf, &len); + if (globals.running == 0 || (!SWITCH_STATUS_IS_BREAK(status) && status != SWITCH_STATUS_SUCCESS)) { + switch_thread_rwlock_unlock(globals.runtime_rwlock); + break; } - if (var && strlen(var) > 1) { - switch_event_add_body(local_event, "%s", var); + /* Did we get data? */ + if (len && len > SWITCH_UUID_FORMATTED_LENGTH) { + rxdata = 1; + process_packet(buf, len); } - - switch_event_fire(&local_event); - } - } + /* If there's data in the IPv6 packet, process it */ + len = MULTICAST_BUFFSIZE - 1; + memset(buf, 0, len + 1); + if (globals.has_udp6 == 1) { + status = switch_socket_recv(globals.udp_socket6, buf, &len); + if (globals.running == 0 || (!SWITCH_STATUS_IS_BREAK(status) && status != SWITCH_STATUS_SUCCESS)) { + switch_thread_rwlock_unlock(globals.runtime_rwlock); + break; + } + /* Did we get data? */ + if (len && len > SWITCH_UUID_FORMATTED_LENGTH) { + rxdata = 1; + process_packet(buf, len); + } + } - if (globals.udp_socket) { - switch_socket_close(globals.udp_socket); - globals.udp_socket = NULL; + /* Nonblocking sockets are required, re-run loop if we got data, else yield */ + if (rxdata == 1) { + switch_thread_rwlock_unlock(globals.runtime_rwlock); + continue; + } + + switch_thread_rwlock_unlock(globals.runtime_rwlock); + switch_yield(500000); } globals.running = 0; free(buf); + globals.runtime_thread_has_to_finish = 0; return SWITCH_STATUS_TERM; } diff --git a/src/mod/event_handlers/mod_event_socket/mod_event_socket.c b/src/mod/event_handlers/mod_event_socket/mod_event_socket.c index d60db15112..0b01e55e66 100644 --- a/src/mod/event_handlers/mod_event_socket/mod_event_socket.c +++ b/src/mod/event_handlers/mod_event_socket/mod_event_socket.c @@ -377,7 +377,7 @@ static void event_handler(switch_event_t *event) if (!uuid || (l->session && strcmp(uuid, switch_core_session_get_uuid(l->session)))) { send = 0; } - if (!strcmp(switch_core_session_get_uuid(l->session), switch_event_get_header_nil(event, "Job-Owner-UUID"))) { + if (l->session && !strcmp(switch_core_session_get_uuid(l->session), switch_event_get_header_nil(event, "Job-Owner-UUID"))) { send = 1; } } diff --git a/src/mod/event_handlers/mod_json_cdr/conf/autoload_configs/json_cdr.conf.xml b/src/mod/event_handlers/mod_json_cdr/conf/autoload_configs/json_cdr.conf.xml index 1862656277..af30c67c07 100644 --- a/src/mod/event_handlers/mod_json_cdr/conf/autoload_configs/json_cdr.conf.xml +++ b/src/mod/event_handlers/mod_json_cdr/conf/autoload_configs/json_cdr.conf.xml @@ -23,6 +23,8 @@ + + diff --git a/src/mod/event_handlers/mod_json_cdr/mod_json_cdr.c b/src/mod/event_handlers/mod_json_cdr/mod_json_cdr.c index fc4794a482..7f66aa425a 100644 --- a/src/mod/event_handlers/mod_json_cdr/mod_json_cdr.c +++ b/src/mod/event_handlers/mod_json_cdr/mod_json_cdr.c @@ -70,6 +70,7 @@ static struct { int disable100continue; int rotate; long auth_scheme; + int timeout; switch_memory_pool_t *pool; switch_event_node_t *node; int encode_values; @@ -361,8 +362,10 @@ static void process_cdr(cdr_data_t *data) switch_curl_easy_setopt(curl_handle, CURLOPT_CAINFO, globals.ssl_cacert_file); } + // tcp timeout + switch_curl_easy_setopt(curl_handle, CURLOPT_TIMEOUT, globals.timeout); + /* these were used for testing, optionally they may be enabled if someone desires - switch_curl_easy_setopt(curl_handle, CURLOPT_TIMEOUT, 120); // tcp timeout switch_curl_easy_setopt(curl_handle, CURLOPT_FOLLOWLOCATION, 1); // 302 recursion level */ @@ -607,6 +610,14 @@ SWITCH_MODULE_LOAD_FUNCTION(mod_json_cdr_load) globals.log_http_and_disk = switch_true(val); } else if (!strcasecmp(var, "log-errors-to-disk")) { globals.log_errors_to_disk = !switch_false(val); + } else if (!strcasecmp(var, "timeout")) { + int tmp = atoi(val); + if (tmp >= 0) { + globals.timeout = tmp; + } else { + globals.timeout = 0; + switch_log_printf(SWITCH_CHANNEL_LOG, SWITCH_LOG_ERROR, "Can't set a negative timeout!\n"); + } } else if (!strcasecmp(var, "delay") && !zstr(val)) { globals.delay = (uint32_t) atoi(val); } else if (!strcasecmp(var, "log-b-leg")) { diff --git a/src/mod/event_handlers/mod_kazoo/kazoo_endpoints.c b/src/mod/event_handlers/mod_kazoo/kazoo_endpoints.c index cb2b28cb26..4ddfeddae4 100644 --- a/src/mod/event_handlers/mod_kazoo/kazoo_endpoints.c +++ b/src/mod/event_handlers/mod_kazoo/kazoo_endpoints.c @@ -222,20 +222,20 @@ static switch_call_cause_t kz_endpoint_outgoing_channel(switch_core_session_t *s } if (!call_fwd_is_valid) { - dest = strdup(endpoint_dial); + dest = endpoint_dial ? strdup(endpoint_dial) : strdup(""); } else if (call_fwd_is_failover) { switch_log_printf(SWITCH_CHANNEL_SESSION_LOG(session), SWITCH_LOG_DEBUG, "setting failover => %s\n", callforward_dial); - dest = strdup(endpoint_dial); + dest = endpoint_dial ? strdup(endpoint_dial) : strdup(""); failover_dial = callforward_dial; } else if (call_fwd_is_substitute) { - switch_log_printf(SWITCH_CHANNEL_SESSION_LOG(session), SWITCH_LOG_DEBUG, "setting call fwd substitute => %s\n", callforward_dial); - dest = strdup(callforward_dial); + dest = callforward_dial ? strdup(callforward_dial) : strdup(""); + switch_log_printf(SWITCH_CHANNEL_SESSION_LOG(session), SWITCH_LOG_DEBUG, "setting call fwd substitute => %s\n", dest); } else { dest = switch_mprintf("%s%s%s", endpoint_dial ? endpoint_dial : "", (endpoint_dial ? endpoint_separator ? endpoint_separator : "," : ""), callforward_dial); switch_log_printf(SWITCH_CHANNEL_SESSION_LOG(session), SWITCH_LOG_DEBUG, "setting call fwd append => %s => %s\n", callforward_dial, dest); } } else { - dest = strdup(endpoint_dial); + dest = endpoint_dial ? strdup(endpoint_dial) : strdup(""); } dialed_user = (char *)switch_xml_attr(x_user, "id"); diff --git a/src/mod/event_handlers/mod_kazoo/kazoo_tweaks.c b/src/mod/event_handlers/mod_kazoo/kazoo_tweaks.c index bb7c792b88..e647871855 100644 --- a/src/mod/event_handlers/mod_kazoo/kazoo_tweaks.c +++ b/src/mod/event_handlers/mod_kazoo/kazoo_tweaks.c @@ -226,7 +226,6 @@ static void kz_tweaks_channel_transferor_event_handler(switch_event_t *event) switch_event_fire(&evt); } switch_core_session_rwunlock(session); - switch_safe_strdup(prv_interaction_id); } else { switch_log_printf(SWITCH_CHANNEL_LOG, SWITCH_LOG_DEBUG, "TRANSFEROR NO UUID SESSION: %s , %s , %s \n", uuid, dest_call_id, dest_peer_uuid); } @@ -240,7 +239,6 @@ static void kz_tweaks_channel_transferor_event_handler(switch_event_t *event) switch_event_fire(&evt); } switch_core_session_rwunlock(session); - switch_safe_strdup(prv_interaction_id); } else { switch_log_printf(SWITCH_CHANNEL_LOG, SWITCH_LOG_DEBUG, "TRANSFEROR NO PEER SESSION: %s , %s , %s \n", uuid, dest_call_id, dest_peer_uuid); } @@ -254,11 +252,9 @@ static void kz_tweaks_channel_transferor_event_handler(switch_event_t *event) switch_event_fire(&evt); } switch_core_session_rwunlock(session); - switch_safe_strdup(prv_interaction_id); } else { switch_log_printf(SWITCH_CHANNEL_LOG, SWITCH_LOG_DEBUG, "TRANSFEROR NO PEER SESSION: %s , %s , %s \n", uuid, dest_call_id, dest_peer_uuid); } - switch_safe_strdup(interaction_id); } else { switch_log_printf(SWITCH_CHANNEL_LOG, SWITCH_LOG_DEBUG, "TRANSFEROR ID = NULL : %s , %s , %s \n", uuid, dest_call_id, dest_peer_uuid); } @@ -441,7 +437,6 @@ static switch_status_t kz_tweaks_handle_replaces_call_id(switch_core_session_t * for(i = 0; bridge_variables[i] != NULL; i++) { const char *val = switch_channel_get_variable_dup(replaced_call_channel, bridge_variables[i], SWITCH_TRUE, -1); switch_channel_set_variable(channel, bridge_variables[i], val); - switch_safe_strdup(val); } if (switch_event_create(&event, SWITCH_EVENT_CHANNEL_DATA) == SWITCH_STATUS_SUCCESS) { switch_channel_event_set_data(channel, event); diff --git a/src/mod/event_handlers/mod_kazoo/kazoo_utils.c b/src/mod/event_handlers/mod_kazoo/kazoo_utils.c index 1986f81717..951707d179 100644 --- a/src/mod/event_handlers/mod_kazoo/kazoo_utils.c +++ b/src/mod/event_handlers/mod_kazoo/kazoo_utils.c @@ -337,12 +337,9 @@ SWITCH_DECLARE(char *) kz_event_expand_headers_check(switch_event_t *event, cons switch_safe_free(expanded); } else { - switch_stream_handle_t stream = { 0 }; char *expanded = NULL; char *expanded_vname = NULL; - SWITCH_STANDARD_STREAM(stream); - if ((expanded_vname = kz_event_expand_headers_check(event, (char *) vname, var_list, api_list, recur+1)) == vname) { expanded_vname = NULL; } else { @@ -359,6 +356,9 @@ SWITCH_DECLARE(char *) kz_event_expand_headers_check(switch_event_t *event, cons func_val = NULL; sub_val = ""; } else { + switch_stream_handle_t stream = { 0 }; + + SWITCH_STANDARD_STREAM(stream); stream.param_event = event; if (kz_expand_api_execute(vname, vval, NULL, &stream) == SWITCH_STATUS_SUCCESS) { func_val = stream.data; diff --git a/src/mod/event_handlers/mod_rayo/Makefile.am b/src/mod/event_handlers/mod_rayo/Makefile.am index f2b7178094..a9ca95d51b 100644 --- a/src/mod/event_handlers/mod_rayo/Makefile.am +++ b/src/mod/event_handlers/mod_rayo/Makefile.am @@ -27,17 +27,17 @@ noinst_PROGRAMS = test/test_iks test/test_nlsml test/test_srgs test_test_iks_SOURCES = test/test_iks.c test_test_iks_CFLAGS = $(AM_CFLAGS) -I. -I$(switch_builddir)/libs/iksemel/include $(PCRE_CFLAGS) -DSWITCH_TEST_BASE_DIR_FOR_CONF=\"${abs_builddir}/test\" -DSWITCH_TEST_BASE_DIR_OVERRIDE=\"${abs_builddir}/test\" test_test_iks_LDFLAGS = $(AM_LDFLAGS) -avoid-version -no-undefined $(freeswitch_LDFLAGS) $(switch_builddir)/libfreeswitch.la $(CORE_LIBS) $(APR_LIBS) -test_test_iks_LDADD = librayomod.la $(IKS_LA) $(PCRE_LIBS) +test_test_iks_LDADD = librayomod.la $(IKS_LA) $(PCRE_LIBS) $(switch_builddir)/libfreeswitch.la test_test_nlsml_SOURCES = test/test_nlsml.c test_test_nlsml_CFLAGS = $(AM_CFLAGS) -I. -I$(switch_builddir)/libs/iksemel/include $(PCRE_CFLAGS) -DSWITCH_TEST_BASE_DIR_FOR_CONF=\"${abs_builddir}/test\" -DSWITCH_TEST_BASE_DIR_OVERRIDE=\"${abs_builddir}/test\" test_test_nlsml_LDFLAGS = $(AM_LDFLAGS) -avoid-version -no-undefined $(freeswitch_LDFLAGS) $(switch_builddir)/libfreeswitch.la $(CORE_LIBS) $(APR_LIBS) -test_test_nlsml_LDADD = librayomod.la $(IKS_LA) $(PCRE_LIBS) +test_test_nlsml_LDADD = librayomod.la $(IKS_LA) $(PCRE_LIBS) $(switch_builddir)/libfreeswitch.la test_test_srgs_SOURCES = test/test_srgs.c test_test_srgs_CFLAGS = $(AM_CFLAGS) -I. -I$(switch_builddir)/libs/iksemel/include $(PCRE_CFLAGS) -DSWITCH_TEST_BASE_DIR_FOR_CONF=\"${abs_builddir}/test\" -DSWITCH_TEST_BASE_DIR_OVERRIDE=\"${abs_builddir}/test\" test_test_srgs_LDFLAGS = $(AM_LDFLAGS) -avoid-version -no-undefined $(freeswitch_LDFLAGS) $(switch_builddir)/libfreeswitch.la $(CORE_LIBS) $(APR_LIBS) -test_test_srgs_LDADD = librayomod.la $(IKS_LA) $(PCRE_LIBS) +test_test_srgs_LDADD = librayomod.la $(IKS_LA) $(PCRE_LIBS) $(switch_builddir)/libfreeswitch.la TESTS = $(noinst_PROGRAMS) diff --git a/src/mod/formats/mod_imagick/mod_imagick.c b/src/mod/formats/mod_imagick/mod_imagick.c index 64ee6762e9..ce789637cf 100644 --- a/src/mod/formats/mod_imagick/mod_imagick.c +++ b/src/mod/formats/mod_imagick/mod_imagick.c @@ -176,7 +176,7 @@ static switch_status_t imagick_file_open(switch_file_handle_t *handle, const cha context->autoplay = 1; } - context->max = 10000; + context->max = 86400000; context->exception = AcquireExceptionInfo(); context->image_info = AcquireImageInfo(); @@ -273,9 +273,9 @@ static switch_status_t imagick_file_open(switch_file_handle_t *handle, const cha } if (context->lazy) { - switch_log_printf(SWITCH_CHANNEL_LOG, SWITCH_LOG_INFO, "Opening File %s, read the first %d page(s)", path, context->lazy); + switch_log_printf(SWITCH_CHANNEL_LOG, SWITCH_LOG_INFO, "Opening File %s, read the first %d page(s)\n", path, context->lazy); } else { - switch_log_printf(SWITCH_CHANNEL_LOG, SWITCH_LOG_INFO, "Opening File %s", path); + switch_log_printf(SWITCH_CHANNEL_LOG, SWITCH_LOG_INFO, "Opening File %s\n", path); } return SWITCH_STATUS_SUCCESS; diff --git a/src/mod/formats/mod_local_stream/mod_local_stream.c b/src/mod/formats/mod_local_stream/mod_local_stream.c index c70d77410c..a38411e954 100644 --- a/src/mod/formats/mod_local_stream/mod_local_stream.c +++ b/src/mod/formats/mod_local_stream/mod_local_stream.c @@ -131,6 +131,7 @@ struct local_stream_source { uint8_t logo_opacity; uint8_t text_opacity; switch_mm_t mm; + int sync; }; typedef struct local_stream_source local_stream_source_t; @@ -362,6 +363,7 @@ static void *SWITCH_THREAD_FUNC read_stream_thread(switch_thread_t *thread, void continue; } + source->sync = 0; switch_buffer_zero(audio_buffer); if (switch_core_file_has_video(&fh, SWITCH_FALSE)) { @@ -907,7 +909,7 @@ static switch_status_t local_stream_file_open(switch_file_handle_t *handle, cons handle->private_info = context; handle->interval = source->interval; switch_log_printf(SWITCH_CHANNEL_LOG, SWITCH_LOG_DEBUG, "Opening Stream [%s] %dhz\n", path, handle->samplerate); - + handle->mm.source_fps = source->mm.source_fps; switch_mutex_init(&context->audio_mutex, SWITCH_MUTEX_NESTED, context->pool); if (switch_buffer_create_dynamic(&context->audio_buffer, 512, 1024, 0) != SWITCH_STATUS_SUCCESS) { switch_log_printf(SWITCH_CHANNEL_LOG, SWITCH_LOG_ERROR, "Memory Error!\n"); @@ -999,14 +1001,19 @@ static switch_status_t local_stream_file_read_video(switch_file_handle_t *handle local_stream_context_t *context = handle->private_info; switch_status_t status; switch_time_t now; - unsigned int fps = (unsigned int)ceil(handle->mm.fps); - unsigned int min_qsize = fps / 2; - unsigned int buf_qsize = 5; + unsigned int min_qsize = 1; + unsigned int buf_qsize = 1; + + handle->mm.source_fps = context->source->mm.source_fps; if (!(context->ready && context->source->ready)) { return SWITCH_STATUS_FALSE; } + if (!context->source->sync) { + return SWITCH_STATUS_BREAK; + } + if (!context->source->has_video) { if (frame) { switch_image_t *src_img = context->source->cover_art; @@ -1040,11 +1047,6 @@ static switch_status_t local_stream_file_read_video(switch_file_handle_t *handle return SWITCH_STATUS_BREAK; } - if (handle->mm.fps >= context->source->mm.source_fps) { - min_qsize = 1; - buf_qsize = 1; - } - while(context->ready && context->source->ready && switch_queue_size(context->video_q) > min_qsize) { if (switch_queue_trypop(context->video_q, &pop) == SWITCH_STATUS_SUCCESS) { switch_image_t *img = (switch_image_t *) pop; @@ -1170,9 +1172,12 @@ static switch_status_t local_stream_file_read(switch_file_handle_t *handle, void if ((bytes = switch_buffer_read(context->audio_buffer, data, need))) { *len = bytes / 2 / context->source->channels; + context->source->sync = 1; } else { size_t blank; + context->source->sync = 0; + switch_assert(handle->samplerate <= 48000); switch_assert(handle->real_channels <= 2); diff --git a/src/mod/formats/mod_opusfile/Makefile.am b/src/mod/formats/mod_opusfile/Makefile.am index 7c776f9d56..6f4919c5b2 100644 --- a/src/mod/formats/mod_opusfile/Makefile.am +++ b/src/mod/formats/mod_opusfile/Makefile.am @@ -22,6 +22,12 @@ noinst_PROGRAMS = test/test_opusfile test_test_opusfile_SOURCES = test/test_opusfile.c test_test_opusfile_CFLAGS = $(AM_CFLAGS) -I./ -I../ -DSWITCH_TEST_BASE_DIR_FOR_CONF=\"${abs_builddir}/test\" -DSWITCH_TEST_BASE_DIR_OVERRIDE=\"${abs_builddir}/test\" $(OPUSFILE_DECODE_CFLAGS) test_test_opusfile_LDFLAGS = $(AM_LDFLAGS) -avoid-version -no-undefined $(freeswitch_LDFLAGS) $(switch_builddir)/libfreeswitch.la $(CORE_LIBS) $(APR_LIBS) $(OPUSFILE_DECODE_LIBS) + +if HAVE_OPUSFILE_ENCODE +test_test_opusfile_CFLAGS += $(OPUSFILE_ENCODE_CFLAGS) -DHAVE_OPUSFILE_ENCODE +test_test_opusfile_LDFLAGS += $(OPUSFILE_ENCODE_LIBS) +endif + test_test_opusfile_LDADD = libopusfilemod.la $(switch_builddir)/libfreeswitch.la TESTS = $(noinst_PROGRAMS) diff --git a/src/mod/formats/mod_opusfile/mod_opusfile.c b/src/mod/formats/mod_opusfile/mod_opusfile.c index 25246a7ced..afd5f51267 100644 --- a/src/mod/formats/mod_opusfile/mod_opusfile.c +++ b/src/mod/formats/mod_opusfile/mod_opusfile.c @@ -42,6 +42,18 @@ #define DEFAULT_RATE 48000 /* default fullband */ #define OPUS_MAX_PCM 5760 /* opus recommended max output buf */ +#define OPUSSTREAM_MAX 64*1024 +#define OGG_MIN_PAGE_SIZE 2400 // this much data buffered before trying to open the incoming stream +#define OGG_MAX_PAGE_SIZE 65307 // a bit less than 64k, standard ogg + +#define PAGES_PER_SEC 4 + +//#define LIMIT_DROP + +#ifdef LIMIT_DROP +#define MIN_OGG_PAYLOAD 40 // drop incoming frames smaller than this (decoder) +#endif + //#undef HAVE_OPUSFILE_ENCODE /*don't encode anything */ SWITCH_MODULE_LOAD_FUNCTION(mod_opusfile_load); @@ -87,6 +99,53 @@ struct opus_file_context { typedef struct opus_file_context opus_file_context; +struct opus_stream_context { + switch_file_t *fd; + OggOpusFile *of; + ogg_int64_t duration; + int output_seekable; + ogg_int64_t pcm_offset; + ogg_int64_t pcm_print_offset; + ogg_int64_t next_pcm_offset; + opus_int64 raw_offset; + ogg_int64_t nsamples; + opus_int32 bitrate; + int li; + int prev_li; + switch_mutex_t *audio_mutex; + switch_buffer_t *audio_buffer; + switch_mutex_t *ogg_mutex; + switch_buffer_t *ogg_buffer; + unsigned char ogg_data[OGG_MAX_PAGE_SIZE * 2]; + unsigned int ogg_data_len; + switch_bool_t read_stream; + switch_bool_t dec_page_ready; + opus_int16 decode_buf[OPUS_MAX_PCM]; + switch_bool_t eof; + switch_thread_rwlock_t *rwlock; + switch_file_handle_t *handle; + size_t samplerate; + int frame_size; + int dec_channels; + size_t err; + opus_int16 *opusbuf; + switch_size_t opusbuflen; +#ifdef HAVE_OPUSFILE_ENCODE + OggOpusEnc *enc; + OggOpusComments *comments; + unsigned char encode_buf[OPUSSTREAM_MAX]; + int encoded_buflen; + size_t samples_encode; + int enc_channels; + unsigned int enc_pagecount; +#endif + unsigned int dec_count; + switch_thread_t *read_stream_thread; + switch_memory_pool_t *pool; +}; + +typedef struct opus_stream_context opus_stream_context_t; + static struct { int debug; } globals; @@ -169,7 +228,6 @@ static switch_status_t switch_opusfile_open(switch_file_handle_t *handle, const { opus_file_context *context; char *ext; - unsigned int flags = 0; int ret; if ((ext = strrchr(path, '.')) == 0) { @@ -190,22 +248,11 @@ static switch_status_t switch_opusfile_open(switch_file_handle_t *handle, const switch_mutex_init(&context->audio_mutex, SWITCH_MUTEX_NESTED, context->pool); - if (switch_test_flag(handle, SWITCH_FILE_FLAG_WRITE)) { - flags |= SWITCH_FOPEN_WRITE | SWITCH_FOPEN_CREATE; - if (switch_test_flag(handle, SWITCH_FILE_WRITE_APPEND) || switch_test_flag(handle, SWITCH_FILE_WRITE_OVER)) { - flags |= SWITCH_FOPEN_READ; - } else { - flags |= SWITCH_FOPEN_TRUNCATE; - } - } - if (switch_test_flag(handle, SWITCH_FILE_FLAG_READ)) { if (switch_buffer_create_dynamic(&context->audio_buffer, TC_BUFFER_SIZE, TC_BUFFER_SIZE * 2, 0) != SWITCH_STATUS_SUCCESS) { switch_log_printf(SWITCH_CHANNEL_LOG, SWITCH_LOG_ERROR, "Memory Error!\n"); goto err; } - - flags |= SWITCH_FOPEN_READ; } handle->samples = 0; @@ -289,9 +336,9 @@ static switch_status_t switch_opusfile_open(switch_file_handle_t *handle, const ogg_int64_t duration; opus_int64 size; duration = op_pcm_total(context->of, context->li); - switch_log_printf(SWITCH_CHANNEL_LOG, SWITCH_LOG_INFO , "[OGG/OPUS File] Duration (samples): %u", (unsigned int)duration); + switch_log_printf(SWITCH_CHANNEL_LOG, SWITCH_LOG_INFO , "[OGG/OPUS File] Duration (samples): %u\n", (unsigned int)duration); size = op_raw_total(context->of, context->li); - switch_log_printf(SWITCH_CHANNEL_LOG, SWITCH_LOG_INFO,"[OGG/OPUS File] Size (bytes): %u", (unsigned int)size); + switch_log_printf(SWITCH_CHANNEL_LOG, SWITCH_LOG_INFO,"[OGG/OPUS File] Size (bytes): %u\n", (unsigned int)size); } tags = op_tags(context->of, context->li); switch_log_printf(SWITCH_CHANNEL_LOG, SWITCH_LOG_INFO, "[OGG/OPUS File] Encoded by: %s\n", tags->vendor); @@ -316,6 +363,7 @@ static switch_status_t switch_opusfile_close(switch_file_handle_t *handle) } #ifdef HAVE_OPUSFILE_ENCODE if (context->enc) { + ope_encoder_drain(context->enc); ope_encoder_destroy(context->enc); } if (context->comments) { @@ -343,7 +391,7 @@ static switch_status_t switch_opusfile_seek(switch_file_handle_t *handle, unsign switch_buffer_zero(context->audio_buffer); ret = op_pcm_seek(context->of, samples); if (globals.debug) { - switch_log_printf(SWITCH_CHANNEL_LOG, SWITCH_LOG_DEBUG,"[OGG/OPUS File] seek samples: [%u]", (unsigned int)samples); + switch_log_printf(SWITCH_CHANNEL_LOG, SWITCH_LOG_DEBUG,"[OGG/OPUS File] seek samples: [%u]\n", (unsigned int)samples); } if (ret == 0) { handle->pos = *cur_sample = samples; @@ -416,7 +464,7 @@ static switch_status_t switch_opusfile_write(switch_file_handle_t *handle, void int err; int mapping_family = 0; - opus_file_context *context = handle->private_info; + opus_file_context *context; if (!handle) { switch_log_printf(SWITCH_CHANNEL_LOG, SWITCH_LOG_ERROR, "Error no handle\n"); @@ -443,17 +491,19 @@ static switch_status_t switch_opusfile_write(switch_file_handle_t *handle, void } if (globals.debug) { - switch_log_printf(SWITCH_CHANNEL_LOG, SWITCH_LOG_DEBUG,"[OGG/OPUS File] write nsamples: [%d]", (int)nsamples); + switch_log_printf(SWITCH_CHANNEL_LOG, SWITCH_LOG_DEBUG,"[OGG/OPUS File] write nsamples: [%d]\n", (int)nsamples); } err = ope_encoder_write(context->enc, (opus_int16 *)data, nsamples); if (err != OPE_OK) { - switch_log_printf(SWITCH_CHANNEL_LOG, SWITCH_LOG_ERROR, "[OGG/OPUS File] Can't encode. err: [%d] [%s]", err, ope_strerror(err)); + switch_log_printf(SWITCH_CHANNEL_LOG, SWITCH_LOG_ERROR, "[OGG/OPUS File] Can't encode. err: [%d] [%s]\n", err, ope_strerror(err)); return SWITCH_STATUS_FALSE; } handle->sample_count += *len; +#else + switch_log_printf(SWITCH_CHANNEL_LOG, SWITCH_LOG_WARNING, "[OGG/OPUS File] Encoding support not built-in, build the module with libopusenc!\n"); #endif return SWITCH_STATUS_SUCCESS; } @@ -479,7 +529,7 @@ SWITCH_STANDARD_API(mod_opusfile_debug) globals.debug = 1; stream->write_function(stream, "OPUSFILE Debug: on\n"); #ifdef HAVE_OPUSFILE_ENCODE - stream->write_function(stream, "Library version (encoding): %s\n", ope_get_version_string()); + stream->write_function(stream, "Library version (encoding): %s ABI: %s\n", ope_get_version_string(), ope_get_abi_version()); #endif } else if (!strcasecmp(cmd, "off")) { globals.debug = 0; @@ -491,6 +541,604 @@ SWITCH_STANDARD_API(mod_opusfile_debug) return SWITCH_STATUS_SUCCESS; } +static switch_status_t switch_opusstream_set_initial(opus_stream_context_t *context) +{ + /* https://www.opus-codec.org/docs/opusfile_api-0.5/group__stream__info.html#ga9272a4a6ac9e01fbc549008f5ff58b4c */ + + if (context->of) { + int ret; + /* docs: "Obtain the PCM offset of the next sample to be read. " */ + ret = op_pcm_tell(context->of); + if (ret != OP_EINVAL) { + context->pcm_offset = ret; + } + context->pcm_print_offset = context->pcm_offset - context->samplerate; + + /* docs: "Obtain the current value of the position indicator for _of." */ + ret = op_raw_tell(context->of); + if (ret != OP_EINVAL) { + context->raw_offset = ret; + } + + /* docs: "Get the channel count of the given link in a (possibly-chained) Ogg Opus stream. " */ + context->dec_channels = op_channel_count(context->of, -1); + if (context->dec_channels == 0) { + context->dec_channels = 1; + } + + context->samplerate = DEFAULT_RATE; + return SWITCH_STATUS_SUCCESS; + } + + return SWITCH_STATUS_FALSE; +} + +static switch_status_t switch_opusstream_stream_info(opus_stream_context_t *context) +{ + const OpusHead *head; + const OpusTags *tags; + opus_int32 bitrate; + + if (context->of) { + + /* docs: "Get the serial number of the given link in a (possibly-chained) Ogg Opus stream. "*/ + switch_log_printf(SWITCH_CHANNEL_LOG, SWITCH_LOG_INFO, "[OGG/OPUS Stream Decode] SerialNO: [%u]\n", op_serialno(context->of, -1)); + bitrate = op_bitrate_instant(context->of); + if (bitrate > 0) { + switch_log_printf(SWITCH_CHANNEL_LOG, SWITCH_LOG_INFO, "[OGG/OPUS Stream Decode] Bitrate: [%d]\n", bitrate); + } + + if(context->pcm_offset!=0){ + switch_log_printf(SWITCH_CHANNEL_LOG, SWITCH_LOG_DEBUG, "[OGG/OPUS Stream Decode] Non-zero starting PCM offset: [%li]\n", + (long)context->pcm_offset); + } + + /* docs: "Retrieve the index of the current link." */ + context->li = op_current_link(context->of); + + /* docs: "Get the ID header information for the given link in a (possibly chained) Ogg Opus stream. " */ + head = op_head(context->of, context->li); + if (head) { + switch_log_printf(SWITCH_CHANNEL_LOG, SWITCH_LOG_INFO, "[OGG/OPUS Stream Decode] Channels: [%i]\n", head->channel_count); + if (head->input_sample_rate) { + context->samplerate = head->input_sample_rate; + switch_log_printf(SWITCH_CHANNEL_LOG, SWITCH_LOG_INFO, "[OGG/OPUS Stream Decode] Original sampling rate: [%lu] Hz\n", + (unsigned long)head->input_sample_rate); + } + } + /*docs: "Returns whether or not the data source being read is seekable."*/ + if (op_seekable(context->of)) { + opus_int64 size; + context->duration = op_pcm_total(context->of, context->li); // page duration + switch_log_printf(SWITCH_CHANNEL_LOG, SWITCH_LOG_INFO , "[OGG/OPUS Stream Decode] Duration (samples): [%u]\n", (unsigned int)context->duration); + size = op_raw_total(context->of, context->li); + switch_log_printf(SWITCH_CHANNEL_LOG, SWITCH_LOG_INFO,"[OGG/OPUS Stream Decode] Size (bytes): [%u]\n", (unsigned int)size); + } + /* docs: "Get the comment header information for the given link in a (possibly chained) Ogg Opus stream." */ + tags = op_tags(context->of, context->li); + switch_log_printf(SWITCH_CHANNEL_LOG, SWITCH_LOG_INFO, "[OGG/OPUS Stream Decode] Encoded by: [%s]\n", tags->vendor); + return SWITCH_STATUS_FALSE; + } + return SWITCH_STATUS_SUCCESS; +} + +static switch_status_t switch_opusstream_stream_decode(opus_stream_context_t *context, void *data, int channels) +{ + int ret; + size_t buf_inuse; + switch_status_t status = SWITCH_STATUS_SUCCESS; + + if (!context->of) { + return SWITCH_STATUS_FALSE; + } + memset(context->decode_buf, 0, sizeof(context->decode_buf)); + switch_mutex_lock(context->audio_mutex); + while (!(context->eof)) { + + if (channels == 1) { + ret = op_read(context->of, (opus_int16 *)context->decode_buf, OPUS_MAX_PCM, NULL); + } else if (channels > 1) { + ret = op_read_stereo(context->of, (opus_int16 *)context->decode_buf, OPUS_MAX_PCM); + } else { + switch_log_printf(SWITCH_CHANNEL_LOG, SWITCH_LOG_ERROR, "[OGG/OPUS Stream] Invalid number of channels!\n"); + switch_goto_status(SWITCH_STATUS_FALSE, end); + } + + if (ret < 0) { + switch(ret) { + case OP_HOLE: /* There was a hole in the data, and some samples may have been skipped. Call this function again to continue decoding past the hole.*/ + if (!context->dec_page_ready) { + if (globals.debug) { + switch_log_printf(SWITCH_CHANNEL_LOG, SWITCH_LOG_DEBUG, "[OGG/OPUS Decoder]: incomplete ogg page, will retry\n"); + } + switch_goto_status(SWITCH_STATUS_SUCCESS, end); + } + case OP_EREAD: /*An underlying read operation failed. This may signal a truncation attack from an source.*/ + + case OP_EFAULT: /* An internal memory allocation failed. */ + + case OP_EIMPL: /*An unseekable stream encountered a new link that used a feature that is not implemented, such as an unsupported channel family.*/ + + case OP_EINVAL: /* The stream was only partially open. */ + + case OP_ENOTFORMAT: /* An unseekable stream encountered a new link that did not have any logical Opus streams in it. */ + + case OP_EBADHEADER: /*An unseekable stream encountered a new link with a required header packet that was not properly formatted, contained illegal values, or was missing altogether.*/ + + case OP_EVERSION: /*An unseekable stream encountered a new link with an ID header that contained an unrecognized version number.*/ + + case OP_EBADPACKET: /*Failed to properly decode the next packet.*/ + + case OP_EBADLINK: /*We failed to find data we had seen before.*/ + + case OP_EBADTIMESTAMP: /*An unseekable stream encountered a new link with a starting timestamp that failed basic validity checks.*/ + + default: + switch_log_printf(SWITCH_CHANNEL_LOG, SWITCH_LOG_ERROR, "[OGG/OPUS Decoder]: error decoding stream: [%d]\n", ret); + switch_goto_status(SWITCH_STATUS_FALSE, end); + } + } else if (ret == 0) { + /*The number of samples returned may be 0 if the buffer was too small to store even a single sample for both channels, or if end-of-file was reached*/ + if (globals.debug) { + switch_log_printf(SWITCH_CHANNEL_LOG, SWITCH_LOG_DEBUG, "[OGG/OPUS Decoder]: EOF reached [%d]\n", ret); + } + + context->eof = TRUE; + break; + } else /* (ret > 0)*/ { + /*The number of samples read per channel on success*/ + switch_buffer_write(context->audio_buffer, (opus_int16 *)context->decode_buf, ret * sizeof(opus_int16) * channels); + buf_inuse = switch_buffer_inuse(context->audio_buffer); + + if (globals.debug) { + switch_log_printf(SWITCH_CHANNEL_LOG, SWITCH_LOG_DEBUG, + "[OGG/OPUS Decoder]: Read samples: %d. Wrote bytes to buffer: [%d] bytes in use: [%u] byte pos stream: [%lu]\n", + ret, (int)(ret * sizeof(int16_t) * channels), (unsigned int)buf_inuse, (long unsigned int)op_raw_tell(context->of)); + } + } + } + +end: + context->eof = FALSE; // for next page + + switch_mutex_unlock(context->audio_mutex); + + return status; +} + +static switch_status_t switch_opusstream_init(switch_codec_t *codec, switch_codec_flag_t flags, const switch_codec_settings_t *codec_settings) +{ + struct opus_stream_context *context = NULL; + int encoding, decoding; +#ifdef HAVE_OPUSFILE_ENCODE + int err; +#endif + + encoding = (flags & SWITCH_CODEC_FLAG_ENCODE); + decoding = (flags & SWITCH_CODEC_FLAG_DECODE); + + if (!(encoding || decoding) || (!(context = switch_core_alloc(codec->memory_pool, sizeof(struct opus_stream_context))))) { + return SWITCH_STATUS_FALSE; + } else { + + memset(context, 0, sizeof(struct opus_stream_context)); + codec->private_info = context; + context->pool = codec->memory_pool; + + switch_thread_rwlock_create(&(context->rwlock), context->pool); + + switch_thread_rwlock_rdlock(context->rwlock); + + switch_mutex_init(&context->audio_mutex, SWITCH_MUTEX_NESTED, context->pool); + switch_mutex_init(&context->ogg_mutex, SWITCH_MUTEX_NESTED, context->pool); + + if (switch_buffer_create_dynamic(&context->audio_buffer, TC_BUFFER_SIZE, TC_BUFFER_SIZE * 2, 0) != SWITCH_STATUS_SUCCESS) { + switch_log_printf(SWITCH_CHANNEL_LOG, SWITCH_LOG_ERROR, "Memory Error!\n"); + switch_thread_rwlock_unlock(context->rwlock); + return SWITCH_STATUS_MEMERR; + } + + if (switch_buffer_create_dynamic(&context->ogg_buffer, TC_BUFFER_SIZE, TC_BUFFER_SIZE * 2, 0) != SWITCH_STATUS_SUCCESS) { + switch_log_printf(SWITCH_CHANNEL_LOG, SWITCH_LOG_ERROR, "Memory Error!\n"); + switch_thread_rwlock_unlock(context->rwlock); + return SWITCH_STATUS_MEMERR; + } + + context->samplerate = codec->implementation->actual_samples_per_second; + context->frame_size = codec->implementation->actual_samples_per_second * (codec->implementation->microseconds_per_packet / 1000) / 1000; + + if (globals.debug) { + switch_log_printf(SWITCH_CHANNEL_LOG, SWITCH_LOG_DEBUG, "[OGG/OPUS Stream] frame_size: [%d]\n", (int)context->frame_size); + } +#ifdef HAVE_OPUSFILE_ENCODE + if (encoding) { + if (!context->comments) { + context->comments = ope_comments_create(); + ope_comments_add(context->comments, "METADATA", "Freeswitch/mod_opusfile"); + } + if (!context->enc) { + int mapping_family = 0; + // opus_multistream_surround_encoder_get_size() in libopus will check these + if ((context->enc_channels > 2) && (context->enc_channels <= 8)) { + mapping_family = 1; + } else if ((context->enc_channels > 8) && (context->enc_channels <= 255)) { + // multichannel/multistream mapping family . https://people.xiph.org/~giles/2013/draft-ietf-codec-oggopus.html#rfc.section.5.1.1 + mapping_family = 255; + } + context->enc = ope_encoder_create_pull(context->comments, !context->samplerate?DEFAULT_RATE:context->samplerate, !context->enc_channels?1:context->enc_channels, mapping_family, &err); + + if (!context->enc) { + switch_log_printf(SWITCH_CHANNEL_LOG, SWITCH_LOG_ERROR, "[OGG/OPUS Stream Encode] Can't create stream. err: [%d] [%s]\n", err, ope_strerror(err)); + switch_thread_rwlock_unlock(context->rwlock); + return SWITCH_STATUS_FALSE; + } else { + switch_log_printf(SWITCH_CHANNEL_LOG, SWITCH_LOG_INFO, "[OGG/OPUS Stream Encode] Stream opened for encoding\n"); + } + ope_encoder_ctl(context->enc, OPUS_SET_COMPLEXITY_REQUEST, 5); + ope_encoder_ctl(context->enc, OPUS_SET_APPLICATION_REQUEST, OPUS_APPLICATION_VOIP); + } + } +#endif + switch_thread_rwlock_unlock(context->rwlock); + return SWITCH_STATUS_SUCCESS; + } +} + +static switch_status_t switch_opusstream_destroy(switch_codec_t *codec) +{ + struct opus_stream_context *context = codec->private_info; + switch_status_t st; + + switch_thread_rwlock_rdlock(context->rwlock); + + if (context->read_stream_thread) { + switch_thread_join(&st, context->read_stream_thread); + if (st == SWITCH_STATUS_SUCCESS) { + switch_log_printf(SWITCH_CHANNEL_LOG, SWITCH_LOG_DEBUG, "[OGG/OPUS Stream Encode/Decode] Joined decoding thread\n"); + } else { + switch_log_printf(SWITCH_CHANNEL_LOG, SWITCH_LOG_DEBUG, "[OGG/OPUS Stream Encode/Decode] Can't join decoding thread\n"); + } + } + + if (context->of) { + op_free(context->of); + } + +#ifdef HAVE_OPUSFILE_ENCODE + if (context->enc) { + ope_encoder_destroy(context->enc); + } + if (context->comments) { + ope_comments_destroy(context->comments); + } + switch_log_printf(SWITCH_CHANNEL_LOG, SWITCH_LOG_DEBUG, "[OGG/OPUS Stream Encode/Decode] Encoded pages: [%u]\n", context->enc_pagecount); +#endif + switch_log_printf(SWITCH_CHANNEL_LOG, SWITCH_LOG_DEBUG, "[OGG/OPUS Stream Encode/Decode] Decoded chunks: [%u]\n", context->dec_count); + if (context->audio_buffer) { + switch_buffer_destroy(&context->audio_buffer); + } + if (context->ogg_buffer) { + switch_buffer_destroy(&context->ogg_buffer); + } + switch_thread_rwlock_unlock(context->rwlock); + codec->private_info = NULL; + switch_log_printf(SWITCH_CHANNEL_LOG, SWITCH_LOG_DEBUG, "[OGG/OPUS Stream Encode/Decode] Stopped processing\n"); + return SWITCH_STATUS_SUCCESS; +} + +static switch_status_t switch_opusstream_encode(switch_codec_t *codec, + switch_codec_t *other_codec, + void *decoded_data, + uint32_t decoded_data_len, + uint32_t decoded_rate, + void *encoded_data, + uint32_t *encoded_data_len, + uint32_t *encoded_rate, + unsigned int *flag) +{ + switch_status_t status = SWITCH_STATUS_SUCCESS; +#ifdef HAVE_OPUSFILE_ENCODE + struct opus_stream_context *context = codec->private_info; + size_t nsamples = (int)decoded_data_len / sizeof(int16_t); + int err, ret; + int len = 0; int thres; + unsigned char *decode_buf = decoded_data; + + if (!context) { + return SWITCH_STATUS_FALSE; + } + + globals.debug = 0; + switch_thread_rwlock_rdlock(context->rwlock); + + if (globals.debug) { + switch_log_printf(SWITCH_CHANNEL_LOG, SWITCH_LOG_DEBUG, + "[OGG/OPUS Stream Encode] : switch_opusfile_stream_encode() decoded_data [%x][%x][%x][%x] nsamples: [%d]\n", + decode_buf[0], decode_buf[1], decode_buf[2], decode_buf[3], (int)nsamples); + switch_log_printf(SWITCH_CHANNEL_LOG, SWITCH_LOG_DEBUG, "[OGG/OPUS Stream Encode] stream write nsamples: [%d]\n", (int)nsamples); + } + if (context->enc_channels == 0) { + context->enc_channels = 1; + } + if (!context->samplerate) { + context->samplerate = DEFAULT_RATE; + } + + if (context->enc) { + // we reach here every 20 ms. + // decoded_data - this can be an interleaved buffer, to do multistream. we’ll need the exact number of channels too. + err = ope_encoder_write(context->enc, (opus_int16 *)decoded_data, nsamples / context->enc_channels); + if (err != OPE_OK) { + switch_log_printf(SWITCH_CHANNEL_LOG, SWITCH_LOG_ERROR, "[OGG/OPUS Stream Encode] can't encode, ret: [%d] [%s]\n", err, ope_strerror(err)); + switch_goto_status(SWITCH_STATUS_FALSE, end); + } + context->samples_encode += nsamples; + } + + thres = context->samplerate/PAGES_PER_SEC; + + if (!(context->samples_encode % thres) && context->samples_encode > context->samplerate) { + if (context->enc) { + unsigned char *vb = context->encode_buf; + int req_flush = 1; + /* OPE_EXPORT int ope_encoder_get_page(OggOpusEnc *enc, unsigned char **page, opus_int32 *len, int flush); */ + ret = ope_encoder_get_page(context->enc, &vb, &len, req_flush); + if (ret == 0) { + /* ope_encoder_get_page(): ret is 1 if there is a page available, 0 if not. */ + if (globals.debug) { + switch_log_printf(SWITCH_CHANNEL_LOG, SWITCH_LOG_DEBUG, "[OGG/OPUS Stream Encode] can't retrieve encoded page, page not ready. ret: [%d]\n", ret); + } + switch_goto_status(SWITCH_STATUS_SUCCESS, end); + } else { + if (globals.debug) { + switch_log_printf(SWITCH_CHANNEL_LOG, SWITCH_LOG_DEBUG, "[OGG/OPUS Stream Encode] retrieved page from encoder. ret [%d] len: [%d] [%p]\n", + ret, len, context->encode_buf); + } + if (len > OGG_MAX_PAGE_SIZE) { + switch_log_printf(SWITCH_CHANNEL_LOG, SWITCH_LOG_ERROR, "[OGG/OPUS Stream Encode] retrieved page bigger than ogg max size!\n"); + switch_goto_status(SWITCH_STATUS_FALSE, end); + } + memcpy(encoded_data, vb, len); + *encoded_data_len = len; + context->enc_pagecount++; + switch_thread_rwlock_unlock(context->rwlock); + return SWITCH_STATUS_SUCCESS; + } + } else { + switch_goto_status(SWITCH_STATUS_FALSE, end); + } + } +end: + *encoded_data_len = 0; + switch_thread_rwlock_unlock(context->rwlock); +#else + switch_log_printf(SWITCH_CHANNEL_LOG, SWITCH_LOG_WARNING, "[OGG/OPUS Stream Encode] Encoding support not built-in, build the module with libopusenc!\n"); +#endif + return status; +} + +// decode_stream_cb(): nbytes is OP_READ_SIZE (builtin limit - libopusfile). +// this is being called by op_read() or op_read_stereo() - we’re giving chunks of pages to be decoded. +static int decode_stream_cb(void *dcontext, unsigned char *data, int nbytes) +{ + opus_stream_context_t *context = (opus_stream_context_t *)dcontext; + unsigned int ret = 0; + + if (!context) { + return 0; + } + + if (globals.debug) { + switch_log_printf(SWITCH_CHANNEL_LOG, SWITCH_LOG_DEBUG, "[OGG/OPUS Stream Decode] decode CB called: context: %p data: %p packet_len: %d\n", + (void *)context, data, nbytes); + switch_log_printf(SWITCH_CHANNEL_LOG, SWITCH_LOG_DEBUG, "[OGG/OPUS Stream Decode] decode_stream_cb(): switch_thread_self(): %lx\n", (unsigned long)(intptr_t)switch_thread_self()); + } + + switch_mutex_lock(context->ogg_mutex); + ret = switch_buffer_read(context->ogg_buffer, context->ogg_data, nbytes); + if (ret == 0) { + data = NULL; + switch_mutex_unlock(context->ogg_mutex); + if (globals.debug) { + switch_log_printf(SWITCH_CHANNEL_LOG, SWITCH_LOG_DEBUG, "[OGG/OPUS Stream Decode] No data. Wanted: [%d] bytes\n", nbytes); + } + return ret; + } + context->dec_count++; + memcpy(data, context->ogg_data, ret); + + if (switch_buffer_inuse(context->ogg_buffer)) { + context->dec_page_ready = 0; + } else { + context->dec_page_ready = 1; + if (globals.debug) { + switch_log_printf(SWITCH_CHANNEL_LOG, SWITCH_LOG_DEBUG, "[OGG/OPUS Stream Decode] buffer is empty, all pages passed to the decoder\n"); + } + + } + switch_mutex_unlock(context->ogg_mutex); + + if (globals.debug) { + switch_log_printf(SWITCH_CHANNEL_LOG, SWITCH_LOG_DEBUG, "[OGG/OPUS Stream Decode] decode_stream_cb(): ret: %u\n", ret); + } + return ret; +} + +const OpusFileCallbacks cb={decode_stream_cb, NULL, NULL, NULL}; + +static void *SWITCH_THREAD_FUNC read_stream_thread(switch_thread_t *thread, void *obj) +{ + opus_stream_context_t *context = (opus_stream_context_t *) obj; + int err = 0; + OggOpusFile *temp_of = NULL; + int buffered_ogg_bytes; + + if (globals.debug) { + switch_log_printf(SWITCH_CHANNEL_LOG, SWITCH_LOG_DEBUG, "[OGG/OPUS Stream Decode] read_stream_thread(): switch_thread_self(): 0x%lx\n", (unsigned long)(intptr_t)switch_thread_self()); + } + switch_thread_rwlock_rdlock(context->rwlock); + switch_mutex_lock(context->ogg_mutex); + + if ((buffered_ogg_bytes = switch_buffer_inuse(context->ogg_buffer))) { + if (buffered_ogg_bytes <= OGG_MAX_PAGE_SIZE) { + switch_buffer_peek(context->ogg_buffer, context->ogg_data, buffered_ogg_bytes); + context->ogg_data_len = buffered_ogg_bytes; + } + } + + /* https://mf4.xiph.org/jenkins/view/opus/job/opusfile-unix/ws/doc/html/group__stream__open__close.html#gad183ecf5fbec5add3a5ccf1e3b1d2593 */ + /* docs: "Open a stream using the given set of callbacks to access it." */ + temp_of = op_open_callbacks(context, &cb, (const unsigned char *)context->ogg_data, context->ogg_data_len, &err); + if (temp_of && (err == 0)) { + context->dec_page_ready = 1; + context->of = temp_of; + if (globals.debug) { + switch_log_printf(SWITCH_CHANNEL_LOG, SWITCH_LOG_INFO, "[OGG/OPUS Stream Decode] Opened stream, installed decoding callback!\n"); + } + switch_opusstream_set_initial(context); + switch_opusstream_stream_info(context); + } else if (err != 0) { + switch (err) { + case OP_EREAD: + // An underlying read, seek, or tell operation failed when it should have succeeded, or we failed to find data in the stream we had seen before. + case OP_EFAULT: + // There was a memory allocation failure, or an internal library error. + case OP_EIMPL: + // The stream used a feature that is not implemented, such as an unsupported channel family. + case OP_EINVAL: + // seek() was implemented and succeeded on this source, but tell() did not, or the starting position indicator was not equal to _initial_bytes. + case OP_ENOTFORMAT: + // The stream contained a link that did not have any logical Opus streams in it. + case OP_EBADHEADER: + // A required header packet was not properly formatted, contained illegal values, or was missing altogether. + case OP_EVERSION: + // An ID header contained an unrecognized version number. + case OP_EBADLINK: + // We failed to find data we had seen before after seeking. + case OP_EBADTIMESTAMP: + // The first or last timestamp in a link failed basic validity checks + default: + context->dec_page_ready = 0; + switch_log_printf(SWITCH_CHANNEL_LOG, SWITCH_LOG_ERROR, "[OGG/OPUS Stream Decode] error opening stream: [%d]\n", err); + } + } + + switch_mutex_unlock(context->ogg_mutex); + switch_thread_rwlock_unlock(context->rwlock); + return NULL; +} + +static void launch_read_stream_thread(opus_stream_context_t *context) +{ + switch_threadattr_t *thd_attr = NULL; + + switch_threadattr_create(&thd_attr, context->pool); + switch_threadattr_stacksize_set(thd_attr, SWITCH_THREAD_STACKSIZE); + switch_thread_create(&context->read_stream_thread, thd_attr, read_stream_thread, context, context->pool); +} + +static switch_status_t switch_opusstream_decode(switch_codec_t *codec, + switch_codec_t *other_codec, + void *encoded_data, + uint32_t encoded_data_len, + uint32_t encoded_rate, + void *decoded_data, + uint32_t *decoded_data_len, + uint32_t *decoded_rate, + unsigned int *flag) +{ + struct opus_stream_context *context = codec->private_info; + size_t bytes = 0; + int ogg_bytes = OGG_MIN_PAGE_SIZE; // min page size before trying to open the incoming stream + size_t rb = 0; + unsigned char *encode_buf = encoded_data; + size_t buffered_ogg_bytes = 0; + switch_status_t status = SWITCH_STATUS_SUCCESS; + + if (!context) { + return SWITCH_STATUS_FALSE; + } + if (globals.debug) { + switch_log_printf(SWITCH_CHANNEL_LOG, SWITCH_LOG_DEBUG, + "[OGG/OPUS Stream Decode] : switch_opusstream_decode() encoded_data [%x][%x][%x][%x] encoded_data_len: [%u]\n", + encode_buf[0], encode_buf[1], encode_buf[2], encode_buf[3], encoded_data_len); + } +#ifdef LIMIT_DROP + if ((encoded_data_len <= MIN_OGG_PAYLOAD) && (encoded_data_len > 0)) { + *decoded_data_len = 0; + if (globals.debug) { + switch_log_printf(SWITCH_CHANNEL_LOG, SWITCH_LOG_DEBUG, "[OGG/OPUS Stream Decode] switch_opusstream_decode(): drop [%u]", (unsigned int)encoded_data_len); + } + return SWITCH_STATUS_SUCCESS; + } +#endif + + switch_thread_rwlock_rdlock(context->rwlock); + switch_mutex_lock(context->ogg_mutex); + memset(context->ogg_data, 0, sizeof(context->ogg_data)); + if (encoded_data_len <= SWITCH_RECOMMENDED_BUFFER_SIZE) { + switch_buffer_write(context->ogg_buffer, encode_buf, encoded_data_len); + + if ((buffered_ogg_bytes = switch_buffer_inuse(context->ogg_buffer)) >= ogg_bytes) { + if (globals.debug) { + switch_log_printf(SWITCH_CHANNEL_LOG, SWITCH_LOG_DEBUG, + "[OGG/OPUS Stream Decode] switch_opusstream_decode() encoded_data [%x][%x][%x][%x] encoded_data_len: %u buffered_ogg_bytes: [%u]\n", + encode_buf[0], encode_buf[1], encode_buf[2], encode_buf[3], encoded_data_len, (unsigned int)buffered_ogg_bytes); + } + if (buffered_ogg_bytes <= OGG_MAX_PAGE_SIZE) { + switch_buffer_peek(context->ogg_buffer, context->ogg_data, buffered_ogg_bytes); + context->ogg_data_len = buffered_ogg_bytes; + } else { + switch_log_printf(SWITCH_CHANNEL_LOG, SWITCH_LOG_ERROR, "[OGG/OPUS Stream Decode] buffered ogg data bigger than max OGG page size, will flush\n"); + *decoded_data_len = 0; + switch_buffer_zero(context->ogg_buffer); + switch_goto_status(SWITCH_STATUS_SUCCESS, end); + } + } + + } else { + switch_log_printf(SWITCH_CHANNEL_LOG, SWITCH_LOG_WARNING, "[OGG/OPUS Stream Decode] too much data to buffer, flushing buffer!\n"); + *decoded_data_len = 0; + switch_buffer_zero(context->ogg_buffer); + switch_goto_status(SWITCH_STATUS_SUCCESS, end); + } + + if ((buffered_ogg_bytes >= ogg_bytes) && encoded_data_len) { + + if (!(op_test(NULL, context->ogg_data, buffered_ogg_bytes))) { + if (!context->read_stream && buffered_ogg_bytes > OGG_MIN_PAGE_SIZE) { + if (globals.debug) { + switch_log_printf(SWITCH_CHANNEL_LOG, SWITCH_LOG_DEBUG, "[OGG/OPUS Stream Decode] launching decoding thread\n"); + } + launch_read_stream_thread(context); + context->read_stream = 1; // mark thread started + } + } + } + if (context->of) { + if (switch_opusstream_stream_decode(context, context->ogg_data, context->dec_channels) == SWITCH_STATUS_FALSE) { + switch_log_printf(SWITCH_CHANNEL_LOG, SWITCH_LOG_ERROR, "[OGG/OPUS Stream Decode] Cannot decode stream\n"); + *decoded_data_len = 0; + switch_goto_status(SWITCH_STATUS_FALSE, end); + } + } + switch_mutex_lock(context->audio_mutex); + bytes = switch_buffer_inuse(context->audio_buffer); + rb = switch_buffer_read(context->audio_buffer, decoded_data, context->frame_size * sizeof(int16_t)); + switch_mutex_unlock(context->audio_mutex); + + if (globals.debug) { + switch_log_printf(SWITCH_CHANNEL_LOG, SWITCH_LOG_DEBUG, "[OGG/OPUS Stream Decode] rb (read from audio_buffer): [%d] bytes in audio buffer: [%d]\n", (int)rb, (int)bytes); + } + + *decoded_data_len = rb ; // bytes +end: + + switch_thread_rwlock_unlock(context->rwlock); + switch_mutex_unlock(context->ogg_mutex); + return status; +} + /* Registration */ static char *supported_formats[SWITCH_MAX_CODECS] = { 0 }; @@ -499,6 +1147,10 @@ SWITCH_MODULE_LOAD_FUNCTION(mod_opusfile_load) { switch_file_interface_t *file_interface; switch_api_interface_t *commands_api_interface; + switch_codec_interface_t *codec_interface; + int mpf = 10000, spf = 80, bpf = 160, count = 2; + int RATES[] = {8000, 16000, 24000, 48000}; + int i; supported_formats[0] = "opus"; @@ -522,13 +1174,48 @@ SWITCH_MODULE_LOAD_FUNCTION(mod_opusfile_load) file_interface->file_set_string = switch_opusfile_set_string; file_interface->file_get_string = switch_opusfile_get_string; - + SWITCH_ADD_CODEC(codec_interface, "OPUSSTREAM"); + + for (i = 0; i < sizeof(RATES) / sizeof(RATES[0]); i++) { +// mono + switch_core_codec_add_implementation(pool, codec_interface, SWITCH_CODEC_TYPE_AUDIO, + 98, /* the IANA code number */ // does not matter + "OPUSSTREAM", /* the IANA code name */ // we just say OPUSSTREAM is an ogg/opus stream + NULL, /* default fmtp to send (can be overridden by the init function) */ + RATES[i], /* samples transferred per second */ // 48000 ! + RATES[i], /* actual samples transferred per second */ + 16 * RATES[i] / 8000, /* bits transferred per second */ + mpf * count, /* number of microseconds per frame */ + spf * RATES[i] / 8000, /* number of samples per frame */ + bpf * RATES[i] / 8000, /* number of bytes per frame decompressed */ + 0, /* number of bytes per frame compressed */ + 1, /* number of channels represented */ + 1, /* number of frames per network packet */ + switch_opusstream_init, switch_opusstream_encode, switch_opusstream_decode, switch_opusstream_destroy); +// stereo + switch_core_codec_add_implementation(pool, codec_interface, SWITCH_CODEC_TYPE_AUDIO, + 98, /* the IANA code number */ // does not matter + "OPUSSTREAM", /* the IANA code name */ // we just say OPUSSTREAM is an ogg/opus stream + NULL, /* default fmtp to send (can be overridden by the init function) */ + RATES[i], /* samples transferred per second */ + RATES[i], /* actual samples transferred per second */ + 16 * RATES[i] / 8000 * 2, /* bits transferred per second */ + mpf * count, /* number of microseconds per frame */ + spf * RATES[i] / 8000 * 2, /* number of samples per frame */ + bpf * RATES[i] / 8000 * 2, /* number of bytes per frame decompressed */ + 0, /* number of bytes per frame compressed */ + 2, /* number of channels represented */ + 1, /* number of frames per network packet */ + switch_opusstream_init, switch_opusstream_encode, switch_opusstream_decode, switch_opusstream_destroy); + } + switch_log_printf(SWITCH_CHANNEL_LOG, SWITCH_LOG_INFO, "mod_opusfile loaded\n"); /* indicate that the module should continue to be loaded */ return SWITCH_STATUS_SUCCESS; } + /* For Emacs: * Local Variables: * mode:c diff --git a/src/mod/formats/mod_opusfile/test/freeswitch.xml b/src/mod/formats/mod_opusfile/test/freeswitch.xml index 80591e86ac..c1fa064524 100644 --- a/src/mod/formats/mod_opusfile/test/freeswitch.xml +++ b/src/mod/formats/mod_opusfile/test/freeswitch.xml @@ -5,6 +5,7 @@ + diff --git a/src/mod/formats/mod_opusfile/test/sounds/audiocheck.net_sin_1000Hz_-3dBFS_6s.opus b/src/mod/formats/mod_opusfile/test/sounds/audiocheck.net_sin_1000Hz_-3dBFS_6s.opus new file mode 100644 index 0000000000..e18be2ec6d Binary files /dev/null and b/src/mod/formats/mod_opusfile/test/sounds/audiocheck.net_sin_1000Hz_-3dBFS_6s.opus differ diff --git a/src/mod/formats/mod_opusfile/test/sounds/audiocheck.net_sin_1000Hz_-3dBFS_6s.wav b/src/mod/formats/mod_opusfile/test/sounds/audiocheck.net_sin_1000Hz_-3dBFS_6s.wav new file mode 100644 index 0000000000..98d4181e47 Binary files /dev/null and b/src/mod/formats/mod_opusfile/test/sounds/audiocheck.net_sin_1000Hz_-3dBFS_6s.wav differ diff --git a/src/mod/formats/mod_opusfile/test/sounds/opusfile-test-ogg.bitstream b/src/mod/formats/mod_opusfile/test/sounds/opusfile-test-ogg.bitstream new file mode 100644 index 0000000000..65c3889027 Binary files /dev/null and b/src/mod/formats/mod_opusfile/test/sounds/opusfile-test-ogg.bitstream differ diff --git a/src/mod/formats/mod_opusfile/test/test_opusfile.c b/src/mod/formats/mod_opusfile/test/test_opusfile.c index 0cb5e8b00b..339047c576 100644 --- a/src/mod/formats/mod_opusfile/test/test_opusfile.c +++ b/src/mod/formats/mod_opusfile/test/test_opusfile.c @@ -32,7 +32,42 @@ #include #include +#include +#include +//#undef HAVE_OPUSFILE_ENCODE + +#define OGG_MIN_PAGE_SIZE 2400 + +static switch_status_t test_detect_tone_in_file(const char *filepath, int rate, int freq) { + teletone_multi_tone_t mt; + teletone_tone_map_t map; + int16_t data[SWITCH_RECOMMENDED_BUFFER_SIZE] = { 0 }; + size_t len = rate * 2 / 100; // in samples + switch_status_t status; + switch_file_handle_t fh = { 0 }; + + status = switch_core_file_open(&fh, filepath, 1, rate, SWITCH_FILE_FLAG_READ | SWITCH_FILE_DATA_SHORT, NULL); + if (status != SWITCH_STATUS_SUCCESS) { + switch_log_printf(SWITCH_CHANNEL_LOG, SWITCH_LOG_ERROR, "Cannot open file [%s]\n", filepath); + return SWITCH_STATUS_FALSE; + } + + mt.sample_rate = rate; + map.freqs[0] = (teletone_process_t)freq; + + teletone_multi_tone_init(&mt, &map); + + while (switch_core_file_read(&fh, &data, &len) == SWITCH_STATUS_SUCCESS) { + if (teletone_multi_tone_detect(&mt, data, len)) { + switch_core_file_close(&fh); + return SWITCH_STATUS_SUCCESS; + } + } + + switch_core_file_close(&fh); + return SWITCH_STATUS_FALSE; +} FST_CORE_BEGIN(".") { @@ -42,6 +77,7 @@ FST_CORE_BEGIN(".") { fst_requires_module("mod_loopback"); fst_requires_module("mod_opusfile"); + fst_requires_module("mod_sndfile"); } FST_SETUP_END() @@ -115,6 +151,178 @@ FST_CORE_BEGIN(".") switch_sleep(1000000); } + FST_TEST_END() + + FST_TEST_BEGIN(opusfile_stream) + { + switch_codec_t read_codec = { 0 }; + switch_status_t status; + switch_codec_settings_t codec_settings = {{ 0 }}; + unsigned char buf[SWITCH_RECOMMENDED_BUFFER_SIZE] = { 0 }; + switch_file_handle_t fhw = { 0 }; + uint32_t flags = 0; + uint32_t rate; + static char tmp_filename[] = "/tmp/opusfile-stream-unit_test.wav"; + char path[4096]; + uint32_t filerate = 48000; + uint32_t torate = 8000; + /*decode*/ + uint32_t decoded_len; + size_t write_len; + unsigned char decbuf[SWITCH_RECOMMENDED_BUFFER_SIZE] = { 0 }; + switch_stream_handle_t stream = { 0 }; + switch_timer_t timer; +#ifdef HAVE_OPUSFILE_ENCODE + switch_file_handle_t fh = { 0 }; + unsigned char encbuf[SWITCH_RECOMMENDED_BUFFER_SIZE] = { 0 }; + switch_codec_t write_codec = { 0 }; + switch_size_t len = 960; + uint32_t encoded_len; + unsigned int pages = 0; + /* + General + Complete name : sounds/audiocheck.net_sin_1000Hz_-3dBFS_6s.wav + Format : Wave + File size : 563 KiB + Duration : 6 s 0 ms + Overall bit rate mode : Constant + Overall bit rate : 768 kb/s + + Audio + Format : PCM + Format settings, Endianness : Little + Format settings, Sign : Signed + Codec ID : 1 + Duration : 6 s 0 ms + Bit rate mode : Constant + Bit rate : 768 kb/s + Channel(s) : 1 channel + Sampling rate : 48.0 kHz + Bit depth : 16 bits + Stream size : 563 KiB (100%) + */ + static char filename[] = "sounds/audiocheck.net_sin_1000Hz_-3dBFS_6s.wav"; +#else + static char opus_filename[] = "sounds/opusfile-test-ogg.bitstream"; + switch_file_t *fd; + switch_size_t flen; +#endif + + status = switch_core_codec_init(&read_codec, + "OPUSSTREAM", + "mod_opusfile", + NULL, + filerate, + 20, + 1, SWITCH_CODEC_FLAG_ENCODE | SWITCH_CODEC_FLAG_DECODE, + &codec_settings, fst_pool); + fst_check(status == SWITCH_STATUS_SUCCESS); + + SWITCH_STANDARD_STREAM(stream); + + switch_api_execute("opusfile_debug", "on", NULL, &stream); + + switch_safe_free(stream.data); + + switch_core_timer_init(&timer, "soft", 20, 960, fst_pool); + +#ifdef HAVE_OPUSFILE_ENCODE + status = switch_core_codec_init(&write_codec, + "OPUSSTREAM", + "mod_opusfile", + NULL, + filerate, + 20, + 1, SWITCH_CODEC_FLAG_ENCODE | SWITCH_CODEC_FLAG_DECODE, + &codec_settings, fst_pool); + fst_check(status == SWITCH_STATUS_SUCCESS); + + sprintf(path, "%s%s%s", SWITCH_GLOBAL_dirs.conf_dir, SWITCH_PATH_SEPARATOR, filename); + + status = switch_core_file_open(&fh, path, 1, filerate, SWITCH_FILE_FLAG_READ | SWITCH_FILE_DATA_SHORT, NULL); + fst_requires(status == SWITCH_STATUS_SUCCESS); + + status = switch_core_file_open(&fhw, tmp_filename, 1, torate, SWITCH_FILE_FLAG_WRITE | SWITCH_FILE_DATA_SHORT, NULL); + fst_requires(status == SWITCH_STATUS_SUCCESS); + + fhw.native_rate = filerate; // make sure we resample to 8000 Hz, because teletone wants this rate + + while (switch_core_file_read(&fh, &buf, &len) == SWITCH_STATUS_SUCCESS) { + + status = switch_core_codec_encode(&write_codec, NULL, &buf, len * sizeof(int16_t), filerate, &encbuf, &encoded_len, &rate, &flags); + fst_check(status == SWITCH_STATUS_SUCCESS); + + if (encoded_len) { + pages++; + status = switch_core_codec_decode(&read_codec, NULL, &encbuf, encoded_len, filerate, &decbuf, &decoded_len, &rate, &flags); + switch_core_timer_next(&timer); + fst_check(status == SWITCH_STATUS_SUCCESS); + write_len = decoded_len / sizeof(int16_t); + if (write_len) switch_core_file_write(&fhw, &decbuf, &write_len); + } + } + + // continue reading, encoded pages are buffered + while (switch_core_codec_decode(&read_codec, NULL, &encbuf, 0, filerate, &decbuf, &decoded_len, &rate, &flags) == SWITCH_STATUS_SUCCESS && decoded_len) { + switch_core_timer_next(&timer); + write_len = decoded_len / sizeof(int16_t); + status = switch_core_file_write(&fhw, &decbuf, &write_len); + fst_check(status == SWITCH_STATUS_SUCCESS); + } + + switch_core_codec_destroy(&write_codec); + + status = switch_core_file_close(&fh); + fst_check(status == SWITCH_STATUS_SUCCESS); + +#else + // the test will perform only decoding + + sprintf(path, "%s%s%s", SWITCH_GLOBAL_dirs.conf_dir, SWITCH_PATH_SEPARATOR, opus_filename); + + // open the file raw and buffer data to the decoder + status = switch_file_open(&fd, path, SWITCH_FOPEN_READ, SWITCH_FPROT_UREAD, fst_pool); + fst_requires(status == SWITCH_STATUS_SUCCESS); + + status = switch_core_file_open(&fhw, tmp_filename, 1, torate, SWITCH_FILE_FLAG_WRITE | SWITCH_FILE_DATA_SHORT, NULL); + fst_requires(status == SWITCH_STATUS_SUCCESS); + + fhw.native_rate = filerate; + + flen = 4096; + while (switch_file_read(fd, &buf, &flen) == SWITCH_STATUS_SUCCESS || flen != 0) { + status = SWITCH_STATUS_SUCCESS; + while (status == SWITCH_STATUS_SUCCESS) { + switch_core_timer_next(&timer); + status = switch_core_codec_decode(&read_codec, NULL, &buf, flen, filerate, &decbuf, &decoded_len, &rate, &flags); + fst_check(status == SWITCH_STATUS_SUCCESS); + write_len = decoded_len / sizeof(int16_t); + if (write_len) switch_core_file_write(&fhw, &decbuf, &write_len); + else break; + } + } +#endif + // continue reading, encoded pages are buffered + while (switch_core_codec_decode(&read_codec, NULL, &buf, 0, filerate, &decbuf, &decoded_len, &rate, &flags) == SWITCH_STATUS_SUCCESS && decoded_len) { + switch_core_timer_next(&timer); + write_len = decoded_len / sizeof(int16_t); + status = switch_core_file_write(&fhw, &decbuf, &write_len); + fst_check(status == SWITCH_STATUS_SUCCESS); + } + + status = switch_core_file_close(&fhw); + fst_check(status == SWITCH_STATUS_SUCCESS); + + switch_core_codec_destroy(&read_codec); + + // final test + status = test_detect_tone_in_file(tmp_filename, torate, 1000 /*Hz*/); + fst_requires(status == SWITCH_STATUS_SUCCESS); + + switch_core_timer_destroy(&timer); + + unlink(tmp_filename); + } FST_TEST_END() } diff --git a/src/mod/formats/mod_png/mod_png.c b/src/mod/formats/mod_png/mod_png.c index 7508dc4fd7..36e38e9c83 100644 --- a/src/mod/formats/mod_png/mod_png.c +++ b/src/mod/formats/mod_png/mod_png.c @@ -76,7 +76,7 @@ static switch_status_t png_file_open(switch_file_handle_t *handle, const char *p } memset(context, 0, sizeof(png_file_context_t)); - context->max = 10000; + context->max = 86400000;; switch_mutex_init(&context->mutex, SWITCH_MUTEX_NESTED, handle->memory_pool); if (handle->params) { diff --git a/src/mod/formats/mod_ssml/Makefile.am b/src/mod/formats/mod_ssml/Makefile.am index ad91a27f29..9a54b5e710 100644 --- a/src/mod/formats/mod_ssml/Makefile.am +++ b/src/mod/formats/mod_ssml/Makefile.am @@ -5,12 +5,25 @@ IKS_DIR=$(switch_srcdir)/libs/iksemel IKS_BUILDDIR=$(switch_builddir)/libs/iksemel IKS_LA=$(IKS_BUILDDIR)/src/libiksemel.la +noinst_LTLIBRARIES = libssmlmod.la +libssmlmod_la_SOURCES = mod_ssml.c +libssmlmod_la_CFLAGS = $(AM_CFLAGS) -I$(IKS_DIR)/include + mod_LTLIBRARIES = mod_ssml.la mod_ssml_la_SOURCES = mod_ssml.c mod_ssml_la_CFLAGS = $(AM_CFLAGS) -I$(IKS_DIR)/include mod_ssml_la_LIBADD = $(switch_builddir)/libfreeswitch.la $(IKS_LA) mod_ssml_la_LDFLAGS = -avoid-version -module -no-undefined -shared +noinst_PROGRAMS = test/test_tts_format + +test_test_tts_format_SOURCES = test/test_tts_format.c +test_test_tts_format_CFLAGS = $(AM_CFLAGS) -I. -DSWITCH_TEST_BASE_DIR_FOR_CONF=\"${abs_builddir}/test\" -DSWITCH_TEST_BASE_DIR_OVERRIDE=\"${abs_builddir}/test\" +test_test_tts_format_LDFLAGS = $(AM_LDFLAGS) -avoid-version -no-undefined $(freeswitch_LDFLAGS) $(switch_builddir)/libfreeswitch.la $(CORE_LIBS) $(APR_LIBS) +test_test_tts_format_LDADD = libssmlmod.la $(IKS_LA) + +TESTS = $(noinst_PROGRAMS) + BUILT_SOURCES=$(IKS_LA) $(IKS_LA): $(IKS_DIR) $(IKS_DIR)/.update diff --git a/src/mod/formats/mod_ssml/mod_ssml.c b/src/mod/formats/mod_ssml/mod_ssml.c index dde13964c8..5783343228 100644 --- a/src/mod/formats/mod_ssml/mod_ssml.c +++ b/src/mod/formats/mod_ssml/mod_ssml.c @@ -472,8 +472,7 @@ static int process_xml_lang(struct ssml_parser *parsed_data, char **atts) while (atts[i]) { if (!strcmp("xml:lang", atts[i])) { if (!zstr(atts[i + 1])) { - strncpy(cur_node->language, atts[i + 1], LANGUAGE_LEN); - cur_node->language[LANGUAGE_LEN - 1] = '\0'; + snprintf(cur_node->language, LANGUAGE_LEN, "%s", atts[i + 1]); } } i += 2; @@ -494,18 +493,15 @@ static int process_voice(struct ssml_parser *parsed_data, char **atts) while (atts[i]) { if (!strcmp("xml:lang", atts[i])) { if (!zstr(atts[i + 1])) { - strncpy(cur_node->language, atts[i + 1], LANGUAGE_LEN); - cur_node->language[LANGUAGE_LEN - 1] = '\0'; + snprintf(cur_node->language, LANGUAGE_LEN, "%s", atts[i + 1]); } } else if (!strcmp("name", atts[i])) { if (!zstr(atts[i + 1])) { - strncpy(cur_node->name, atts[i + 1], NAME_LEN); - cur_node->name[NAME_LEN - 1] = '\0'; + snprintf(cur_node->name, NAME_LEN, "%s", atts[i + 1]); } } else if (!strcmp("gender", atts[i])) { if (!zstr(atts[i + 1])) { - strncpy(cur_node->gender, atts[i + 1], GENDER_LEN); - cur_node->gender[GENDER_LEN - 1] = '\0'; + snprintf(cur_node->gender, GENDER_LEN, "%s", atts[i + 1]); } } i += 2; @@ -633,8 +629,7 @@ static int tag_hook(void *user_data, char *name, char **atts, int type) } new_node->tts_voice = NULL; new_node->say_macro = NULL; - strncpy(new_node->tag_name, name, TAG_LEN); - new_node->tag_name[TAG_LEN - 1] = '\0'; + snprintf(new_node->tag_name, TAG_LEN, "%s", name); parsed_data->cur_node = new_node; result = process_tag(parsed_data, name, atts); } @@ -743,8 +738,7 @@ static int process_cdata_tts(struct ssml_parser *parsed_data, char *data, size_t /* try macro */ to_say = malloc(len + 1); switch_assert(to_say); - strncpy(to_say, data, len); - to_say[len] = '\0'; + snprintf(to_say, len + 1, "%s", data); if (!cur_node->say_macro || !get_file_from_macro(parsed_data, to_say)) { /* use voice instead */ if (!get_file_from_voice(parsed_data, to_say)) { @@ -941,6 +935,12 @@ static switch_status_t tts_file_open(switch_file_handle_t *handle, const char *p memset(context, 0, sizeof(*context)); context->flags = SWITCH_SPEECH_FLAG_NONE; if ((status = switch_core_speech_open(&context->sh, module, voice, handle->samplerate, handle->interval, handle->channels, &context->flags, NULL)) == SWITCH_STATUS_SUCCESS) { + if (handle->params) { + const char *channel_uuid = switch_event_get_header(handle->params, "channel-uuid"); + if (!zstr(channel_uuid)) { + switch_core_speech_text_param_tts(&context->sh, "channel-uuid", channel_uuid); + } + } if ((status = switch_core_speech_feed_tts(&context->sh, document, &context->flags)) == SWITCH_STATUS_SUCCESS) { handle->channels = 1; handle->samples = 0; diff --git a/src/mod/formats/mod_ssml/test/freeswitch.xml b/src/mod/formats/mod_ssml/test/freeswitch.xml new file mode 100644 index 0000000000..eb2f8bda7e --- /dev/null +++ b/src/mod/formats/mod_ssml/test/freeswitch.xml @@ -0,0 +1,36 @@ + + +
+ + + + + + + + + + + + + + + + + + + + + +
+ +
+ + + + + + + +
+
diff --git a/src/mod/formats/mod_ssml/test/test_tts_format.c b/src/mod/formats/mod_ssml/test/test_tts_format.c new file mode 100644 index 0000000000..d3edaf6300 --- /dev/null +++ b/src/mod/formats/mod_ssml/test/test_tts_format.c @@ -0,0 +1,66 @@ +/* + * FreeSWITCH Modular Media Switching Software Library / Soft-Switch Application + * Copyright (C) 2005-2021, Anthony Minessale II + * + * Version: MPL 1.1 + * + * The contents of this file are subject to the Mozilla Public License Version + * 1.1 (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * http://www.mozilla.org/MPL/ + * + * Software distributed under the License is distributed on an "AS IS" basis, + * WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License + * for the specific language governing rights and limitations under the + * License. + * + * The Original Code is FreeSWITCH Modular Media Switching Software Library / Soft-Switch Application + * + * The Initial Developer of the Original Code is + * Anthony Minessale II + * Portions created by the Initial Developer are Copyright (C) + * the Initial Developer. All Rights Reserved. + * + * Contributor(s): + * Chris Rienzo + * + * + * test_tts_format.c -- tests for tts:// file format + * + */ +#include +#include + +FST_CORE_BEGIN(".") + +FST_MODULE_BEGIN(mod_ssml, test_tts_format) + +FST_SETUP_BEGIN() +{ + fst_requires_module("mod_test"); +} +FST_SETUP_END() + +FST_TEARDOWN_BEGIN() +{ + switch_core_set_variable("mod_test_tts_must_have_channel_uuid", "false"); +} +FST_TEARDOWN_END() + +FST_SESSION_BEGIN(tts_channel_uuid) +{ + char *tts_without_channel_uuid = "tts://test||This is a test"; + char *tts_with_channel_uuid = switch_core_session_sprintf(fst_session, "{channel-uuid=%s}tts://test||This is a test", switch_core_session_get_uuid(fst_session)); + switch_status_t status; + switch_core_set_variable("mod_test_tts_must_have_channel_uuid", "true"); + status = switch_ivr_play_file(fst_session, NULL, tts_without_channel_uuid, NULL); + fst_xcheck(status != SWITCH_STATUS_SUCCESS, "Expect channel UUID not to be delivered to TTS module"); + + status = switch_ivr_play_file(fst_session, NULL, tts_with_channel_uuid, NULL); + fst_xcheck(status == SWITCH_STATUS_SUCCESS, "Expect channel UUID to be delivered to TTS module"); +} +FST_SESSION_END() + +FST_MODULE_END() + +FST_CORE_END() diff --git a/src/mod/languages/mod_lua/freeswitch_lua.cpp b/src/mod/languages/mod_lua/freeswitch_lua.cpp index 50d0778336..5d89aa28f9 100644 --- a/src/mod/languages/mod_lua/freeswitch_lua.cpp +++ b/src/mod/languages/mod_lua/freeswitch_lua.cpp @@ -568,11 +568,11 @@ void JSON::LuaTable2cJSON(lua_State *L, int index, cJSON **json) switch_assert(*json); - if (lua_isnumber(L, -2)) { + if (lua_type(L, -2) == LUA_TNUMBER) { ADDITEM(*json, key, cJSON_CreateNumber(lua_tonumber(L, -2))); - } else if (lua_isstring(L, -2)) { + } else if (lua_type(L, -2) == LUA_TSTRING) { ADDITEM(*json, key, cJSON_CreateString(lua_tostring(L, -2))); - } else if (lua_isboolean(L, -2)) { + } else if (lua_type(L, -2) == LUA_TBOOLEAN) { ADDITEM(*json, key, cJSON_CreateBool(lua_toboolean(L, -2))); } else if (lua_isnil(L, -2)) { ADDITEM(*json, key, cJSON_CreateNull()); diff --git a/src/mod/languages/mod_lua/hack.diff b/src/mod/languages/mod_lua/hack.diff index 907efb0d7e..95ec620feb 100644 --- a/src/mod/languages/mod_lua/hack.diff +++ b/src/mod/languages/mod_lua/hack.diff @@ -53,6 +53,22 @@ result = (bool)(arg1)->test_reactive(arg2,arg3,arg4); lua_pushboolean(L,(int)(result!=0)); SWIG_arg++; return SWIG_arg; +@@ -9516,6 +9516,7 @@ static int _wrap_Dbh_test_reactive__SWIG_1(lua_State* L) { + + arg2 = (char *)lua_tostring(L, 2); + arg3 = (char *)lua_tostring(L, 3); ++ switch_assert(arg1); + result = (bool)(arg1)->test_reactive(arg2,arg3); + lua_pushboolean(L,(int)(result!=0)); SWIG_arg++; + return SWIG_arg; +@@ -9543,6 +9544,7 @@ static int _wrap_Dbh_test_reactive__SWIG_2(lua_State* L) { + } + + arg2 = (char *)lua_tostring(L, 2); ++ switch_assert(arg1); + result = (bool)(arg1)->test_reactive(arg2); + lua_pushboolean(L,(int)(result!=0)); SWIG_arg++; + return SWIG_arg; @@ -9672,6 +9673,7 @@ static int _wrap_Dbh_query(lua_State* L) { (&arg3)->idx = 3; } diff --git a/src/mod/languages/mod_lua/mod_lua_wrap.cpp b/src/mod/languages/mod_lua/mod_lua_wrap.cpp index 7d91ba33ba..93ba825557 100644 --- a/src/mod/languages/mod_lua/mod_lua_wrap.cpp +++ b/src/mod/languages/mod_lua/mod_lua_wrap.cpp @@ -9548,6 +9548,7 @@ static int _wrap_Dbh_test_reactive__SWIG_1(lua_State* L) { arg2 = (char *)lua_tostring(L, 2); arg3 = (char *)lua_tostring(L, 3); + switch_assert(arg1); result = (bool)(arg1)->test_reactive(arg2,arg3); lua_pushboolean(L,(int)(result!=0)); SWIG_arg++; return SWIG_arg; @@ -9575,6 +9576,7 @@ static int _wrap_Dbh_test_reactive__SWIG_2(lua_State* L) { } arg2 = (char *)lua_tostring(L, 2); + switch_assert(arg1); result = (bool)(arg1)->test_reactive(arg2); lua_pushboolean(L,(int)(result!=0)); SWIG_arg++; return SWIG_arg; diff --git a/src/mod/languages/mod_lua/test/test_json.lua b/src/mod/languages/mod_lua/test/test_json.lua index b8f358f816..9ac2c06284 100644 --- a/src/mod/languages/mod_lua/test/test_json.lua +++ b/src/mod/languages/mod_lua/test/test_json.lua @@ -108,5 +108,11 @@ freeswitch.consoleLog("INFO", ret .. "\n") ret = json:execute2(json:encode(cmd)) freeswitch.consoleLog("INFO", ret .. "\n") +sn = json:encode({s = "1001", n = 1002}) +freeswitch.consoleLog("INFO", sn .. "\n") +ret = json:decode(sn) +assert(ret.s == "1001") +assert(ret.n == 1002) + -- assert(false) stream:write("+OK") diff --git a/src/mod/languages/mod_managed/freeswitch_wrap.cxx b/src/mod/languages/mod_managed/freeswitch_wrap.cxx index 3ada536f66..7443ed5232 100644 --- a/src/mod/languages/mod_managed/freeswitch_wrap.cxx +++ b/src/mod/languages/mod_managed/freeswitch_wrap.cxx @@ -5947,6 +5947,30 @@ SWIGEXPORT void SWIGSTDCALL CSharp_FreeSWITCHfNative_delete_switch_t38_options_t } +SWIGEXPORT void * SWIGSTDCALL CSharp_FreeSWITCHfNative_switch_core_session_type_check___(void * jarg1) { + void * jresult ; + switch_core_session_t *arg1 = (switch_core_session_t *) 0 ; + switch_core_session_t *result = 0 ; + + arg1 = (switch_core_session_t *)jarg1; + result = (switch_core_session_t *)switch_core_session_type_check(arg1); + jresult = (void *)result; + return jresult; +} + + +SWIGEXPORT char * SWIGSTDCALL CSharp_FreeSWITCHfNative_switch_const_char_type_check___(char * jarg1) { + char * jresult ; + char *arg1 = (char *) 0 ; + char *result = 0 ; + + arg1 = (char *)jarg1; + result = (char *)switch_const_char_type_check((char const *)arg1); + jresult = SWIG_csharp_string_callback((const char *)result); + return jresult; +} + + SWIGEXPORT void SWIGSTDCALL CSharp_FreeSWITCHfNative_switch_vid_params_t_width_set___(void * jarg1, unsigned long jarg2) { switch_vid_params_s *arg1 = (switch_vid_params_s *) 0 ; uint32_t arg2 ; @@ -7831,6 +7855,28 @@ SWIGEXPORT float SWIGSTDCALL CSharp_FreeSWITCHfNative_switch_mm_t_source_fps_get } +SWIGEXPORT void SWIGSTDCALL CSharp_FreeSWITCHfNative_switch_mm_t_source_kps_set___(void * jarg1, int jarg2) { + switch_mm_s *arg1 = (switch_mm_s *) 0 ; + int arg2 ; + + arg1 = (switch_mm_s *)jarg1; + arg2 = (int)jarg2; + if (arg1) (arg1)->source_kps = arg2; +} + + +SWIGEXPORT int SWIGSTDCALL CSharp_FreeSWITCHfNative_switch_mm_t_source_kps_get___(void * jarg1) { + int jresult ; + switch_mm_s *arg1 = (switch_mm_s *) 0 ; + int result; + + arg1 = (switch_mm_s *)jarg1; + result = (int) ((arg1)->source_kps); + jresult = result; + return jresult; +} + + SWIGEXPORT void SWIGSTDCALL CSharp_FreeSWITCHfNative_switch_mm_t_vbuf_set___(void * jarg1, int jarg2) { switch_mm_s *arg1 = (switch_mm_s *) 0 ; int arg2 ; @@ -9781,6 +9827,28 @@ SWIGEXPORT int SWIGSTDCALL CSharp_FreeSWITCHfNative_switch_thread_data_t_alloc_g } +SWIGEXPORT void SWIGSTDCALL CSharp_FreeSWITCHfNative_switch_thread_data_t_running_set___(void * jarg1, int jarg2) { + switch_thread_data_s *arg1 = (switch_thread_data_s *) 0 ; + int arg2 ; + + arg1 = (switch_thread_data_s *)jarg1; + arg2 = (int)jarg2; + if (arg1) (arg1)->running = arg2; +} + + +SWIGEXPORT int SWIGSTDCALL CSharp_FreeSWITCHfNative_switch_thread_data_t_running_get___(void * jarg1) { + int jresult ; + switch_thread_data_s *arg1 = (switch_thread_data_s *) 0 ; + int result; + + arg1 = (switch_thread_data_s *)jarg1; + result = (int) ((arg1)->running); + jresult = result; + return jresult; +} + + SWIGEXPORT void SWIGSTDCALL CSharp_FreeSWITCHfNative_switch_thread_data_t_pool_set___(void * jarg1, void * jarg2) { switch_thread_data_s *arg1 = (switch_thread_data_s *) 0 ; switch_memory_pool_t *arg2 = (switch_memory_pool_t *) 0 ; @@ -12069,18 +12137,6 @@ SWIGEXPORT void * SWIGSTDCALL CSharp_FreeSWITCHfNative_switch_must_realloc___(vo } -SWIGEXPORT char * SWIGSTDCALL CSharp_FreeSWITCHfNative_switch_must_strdup___(char * jarg1) { - char * jresult ; - char *arg1 = (char *) 0 ; - char *result = 0 ; - - arg1 = (char *)jarg1; - result = (char *)switch_must_strdup((char const *)arg1); - jresult = SWIG_csharp_string_callback((const char *)result); - return jresult; -} - - SWIGEXPORT void SWIGSTDCALL CSharp_FreeSWITCHfNative_switch_core_screen_size___(void * jarg1, void * jarg2) { int *arg1 = (int *) 0 ; int *arg2 = (int *) 0 ; @@ -13263,6 +13319,20 @@ SWIGEXPORT int SWIGSTDCALL CSharp_FreeSWITCHfNative_switch_core_session_set_uuid } +SWIGEXPORT int SWIGSTDCALL CSharp_FreeSWITCHfNative_switch_core_session_set_external_id___(void * jarg1, char * jarg2) { + int jresult ; + switch_core_session_t *arg1 = (switch_core_session_t *) 0 ; + char *arg2 = (char *) 0 ; + switch_status_t result; + + arg1 = (switch_core_session_t *)jarg1; + arg2 = (char *)jarg2; + result = (switch_status_t)switch_core_session_set_external_id(arg1,(char const *)arg2); + jresult = (int)result; + return jresult; +} + + SWIGEXPORT void SWIGSTDCALL CSharp_FreeSWITCHfNative_switch_core_session_perform_destroy___(void * jarg1, char * jarg2, char * jarg3, int jarg4) { switch_core_session_t **arg1 = (switch_core_session_t **) 0 ; char *arg2 = (char *) 0 ; @@ -13397,6 +13467,20 @@ SWIGEXPORT int SWIGSTDCALL CSharp_FreeSWITCHfNative_switch_core_session_thread_p } +SWIGEXPORT int SWIGSTDCALL CSharp_FreeSWITCHfNative_switch_thread_pool_wait___(void * jarg1, int jarg2) { + int jresult ; + switch_thread_data_t *arg1 = (switch_thread_data_t *) 0 ; + int arg2 ; + switch_status_t result; + + arg1 = (switch_thread_data_t *)jarg1; + arg2 = (int)jarg2; + result = (switch_status_t)switch_thread_pool_wait(arg1,arg2); + jresult = (int)result; + return jresult; +} + + SWIGEXPORT void * SWIGSTDCALL CSharp_FreeSWITCHfNative_switch_core_session_get_channel___(void * jarg1) { void * jresult ; switch_core_session_t *arg1 = (switch_core_session_t *) 0 ; @@ -13453,6 +13537,18 @@ SWIGEXPORT char * SWIGSTDCALL CSharp_FreeSWITCHfNative_switch_core_session_get_u } +SWIGEXPORT char * SWIGSTDCALL CSharp_FreeSWITCHfNative_switch_core_session_get_external_id___(void * jarg1) { + char * jresult ; + switch_core_session_t *arg1 = (switch_core_session_t *) 0 ; + char *result = 0 ; + + arg1 = (switch_core_session_t *)jarg1; + result = (char *)switch_core_session_get_external_id(arg1); + jresult = SWIG_csharp_string_callback((const char *)result); + return jresult; +} + + SWIGEXPORT int SWIGSTDCALL CSharp_FreeSWITCHfNative_switch_core_session_set_loglevel___(void * jarg1, int jarg2) { int jresult ; switch_core_session_t *arg1 = (switch_core_session_t *) 0 ; @@ -14673,6 +14769,20 @@ SWIGEXPORT int SWIGSTDCALL CSharp_FreeSWITCHfNative_switch_core_hash_destroy___( } +SWIGEXPORT int SWIGSTDCALL CSharp_FreeSWITCHfNative_switch_core_hash_insert_pointer___(void * jarg1, void * jarg2) { + int jresult ; + switch_hash_t *arg1 = (switch_hash_t *) 0 ; + void *arg2 = (void *) 0 ; + switch_status_t result; + + arg1 = (switch_hash_t *)jarg1; + arg2 = (void *)jarg2; + result = (switch_status_t)switch_core_hash_insert_pointer(arg1,(void const *)arg2); + jresult = (int)result; + return jresult; +} + + SWIGEXPORT int SWIGSTDCALL CSharp_FreeSWITCHfNative_switch_core_hash_insert_auto_free___(void * jarg1, char * jarg2, void * jarg3) { int jresult ; switch_hash_t *arg1 = (switch_hash_t *) 0 ; @@ -14689,6 +14799,22 @@ SWIGEXPORT int SWIGSTDCALL CSharp_FreeSWITCHfNative_switch_core_hash_insert_auto } +SWIGEXPORT int SWIGSTDCALL CSharp_FreeSWITCHfNative_switch_core_hash_insert_dup_auto_free___(void * jarg1, char * jarg2, char * jarg3) { + int jresult ; + switch_hash_t *arg1 = (switch_hash_t *) 0 ; + char *arg2 = (char *) 0 ; + char *arg3 = (char *) 0 ; + switch_status_t result; + + arg1 = (switch_hash_t *)jarg1; + arg2 = (char *)jarg2; + arg3 = (char *)jarg3; + result = (switch_status_t)switch_core_hash_insert_dup_auto_free(arg1,(char const *)arg2,(char const *)arg3); + jresult = (int)result; + return jresult; +} + + SWIGEXPORT int SWIGSTDCALL CSharp_FreeSWITCHfNative_switch_core_hash_insert_destructor___(void * jarg1, char * jarg2, void * jarg3, void * jarg4) { int jresult ; switch_hash_t *arg1 = (switch_hash_t *) 0 ; @@ -14707,6 +14833,42 @@ SWIGEXPORT int SWIGSTDCALL CSharp_FreeSWITCHfNative_switch_core_hash_insert_dest } +SWIGEXPORT void * SWIGSTDCALL CSharp_FreeSWITCHfNative_switch_core_hash_insert_alloc_destructor___(void * jarg1, char * jarg2, unsigned long jarg3, void * jarg4) { + void * jresult ; + switch_hash_t *arg1 = (switch_hash_t *) 0 ; + char *arg2 = (char *) 0 ; + size_t arg3 ; + hashtable_destructor_t arg4 = (hashtable_destructor_t) 0 ; + void *result = 0 ; + + arg1 = (switch_hash_t *)jarg1; + arg2 = (char *)jarg2; + arg3 = (size_t)jarg3; + arg4 = (hashtable_destructor_t)jarg4; + result = (void *)switch_core_hash_insert_alloc_destructor(arg1,(char const *)arg2,arg3,arg4); + jresult = (void *)result; + return jresult; +} + + +SWIGEXPORT int SWIGSTDCALL CSharp_FreeSWITCHfNative_switch_core_hash_insert_dup_destructor___(void * jarg1, char * jarg2, char * jarg3, void * jarg4) { + int jresult ; + switch_hash_t *arg1 = (switch_hash_t *) 0 ; + char *arg2 = (char *) 0 ; + char *arg3 = (char *) 0 ; + hashtable_destructor_t arg4 = (hashtable_destructor_t) 0 ; + switch_status_t result; + + arg1 = (switch_hash_t *)jarg1; + arg2 = (char *)jarg2; + arg3 = (char *)jarg3; + arg4 = (hashtable_destructor_t)jarg4; + result = (switch_status_t)switch_core_hash_insert_dup_destructor(arg1,(char const *)arg2,(char const *)arg3,arg4); + jresult = (int)result; + return jresult; +} + + SWIGEXPORT int SWIGSTDCALL CSharp_FreeSWITCHfNative_switch_core_hash_insert_locked___(void * jarg1, char * jarg2, void * jarg3, void * jarg4) { int jresult ; switch_hash_t *arg1 = (switch_hash_t *) 0 ; @@ -21127,15 +21289,17 @@ SWIGEXPORT int SWIGSTDCALL CSharp_FreeSWITCHfNative_get_addr_int___(void * jarg1 } -SWIGEXPORT int SWIGSTDCALL CSharp_FreeSWITCHfNative_switch_cmp_addr___(void * jarg1, void * jarg2) { +SWIGEXPORT int SWIGSTDCALL CSharp_FreeSWITCHfNative_switch_cmp_addr___(void * jarg1, void * jarg2, int jarg3) { int jresult ; switch_sockaddr_t *arg1 = (switch_sockaddr_t *) 0 ; switch_sockaddr_t *arg2 = (switch_sockaddr_t *) 0 ; + switch_bool_t arg3 ; int result; arg1 = (switch_sockaddr_t *)jarg1; arg2 = (switch_sockaddr_t *)jarg2; - result = (int)switch_cmp_addr(arg1,arg2); + arg3 = (switch_bool_t)jarg3; + result = (int)switch_cmp_addr(arg1,arg2,arg3); jresult = result; return jresult; } @@ -21331,6 +21495,34 @@ SWIGEXPORT int SWIGSTDCALL CSharp_FreeSWITCHfNative_switch_safe_atoi___(char * j } +SWIGEXPORT long SWIGSTDCALL CSharp_FreeSWITCHfNative_switch_safe_atol___(char * jarg1, long jarg2) { + long jresult ; + char *arg1 = (char *) 0 ; + long arg2 ; + long result; + + arg1 = (char *)jarg1; + arg2 = (long)jarg2; + result = (long)switch_safe_atol((char const *)arg1,arg2); + jresult = result; + return jresult; +} + + +SWIGEXPORT long long SWIGSTDCALL CSharp_FreeSWITCHfNative_switch_safe_atoll___(char * jarg1, long long jarg2) { + long long jresult ; + char *arg1 = (char *) 0 ; + long long arg2 ; + long long result; + + arg1 = (char *)jarg1; + arg2 = (long long)jarg2; + result = (long long)switch_safe_atoll((char const *)arg1,arg2); + jresult = result; + return jresult; +} + + SWIGEXPORT char * SWIGSTDCALL CSharp_FreeSWITCHfNative_switch_safe_strdup___(char * jarg1) { char * jresult ; char *arg1 = (char *) 0 ; @@ -21974,6 +22166,20 @@ SWIGEXPORT int SWIGSTDCALL CSharp_FreeSWITCHfNative_switch_is_file_path___(char } +SWIGEXPORT int SWIGSTDCALL CSharp_FreeSWITCHfNative_switch_filecmp___(char * jarg1, char * jarg2) { + int jresult ; + char *arg1 = (char *) 0 ; + char *arg2 = (char *) 0 ; + int result; + + arg1 = (char *)jarg1; + arg2 = (char *)jarg2; + result = (int)switch_filecmp((char const *)arg1,(char const *)arg2); + jresult = result; + return jresult; +} + + SWIGEXPORT char * SWIGSTDCALL CSharp_FreeSWITCHfNative_switch_parse_audio_col___(int jarg1) { char * jresult ; switch_audio_col_t arg1 ; @@ -23285,6 +23491,30 @@ SWIGEXPORT int SWIGSTDCALL CSharp_FreeSWITCHfNative_switch_digest_string___(char } +SWIGEXPORT char * SWIGSTDCALL CSharp_FreeSWITCHfNative_switch_must_strdup___(char * jarg1) { + char * jresult ; + char *arg1 = (char *) 0 ; + char *result = 0 ; + + arg1 = (char *)jarg1; + result = (char *)switch_must_strdup((char const *)arg1); + jresult = SWIG_csharp_string_callback((const char *)result); + return jresult; +} + + +SWIGEXPORT char * SWIGSTDCALL CSharp_FreeSWITCHfNative_switch_memory_usage_stream___(void * jarg1) { + char * jresult ; + switch_stream_handle_t *arg1 = (switch_stream_handle_t *) 0 ; + char *result = 0 ; + + arg1 = (switch_stream_handle_t *)jarg1; + result = (char *)switch_memory_usage_stream(arg1); + jresult = SWIG_csharp_string_callback((const char *)result); + return jresult; +} + + SWIGEXPORT void SWIGSTDCALL CSharp_FreeSWITCHfNative_profile_node_t_var_set___(void * jarg1, char * jarg2) { profile_node_s *arg1 = (profile_node_s *) 0 ; char *arg2 = (char *) 0 ; @@ -36307,6 +36537,24 @@ SWIGEXPORT int SWIGSTDCALL CSharp_FreeSWITCHfNative_switch_channel_set_variable_ } +SWIGEXPORT int SWIGSTDCALL CSharp_FreeSWITCHfNative_switch_channel_set_variable_strip_quotes_var_check___(void * jarg1, char * jarg2, char * jarg3, int jarg4) { + int jresult ; + switch_channel_t *arg1 = (switch_channel_t *) 0 ; + char *arg2 = (char *) 0 ; + char *arg3 = (char *) 0 ; + switch_bool_t arg4 ; + switch_status_t result; + + arg1 = (switch_channel_t *)jarg1; + arg2 = (char *)jarg2; + arg3 = (char *)jarg3; + arg4 = (switch_bool_t)jarg4; + result = (switch_status_t)switch_channel_set_variable_strip_quotes_var_check(arg1,(char const *)arg2,(char const *)arg3,arg4); + jresult = (int)result; + return jresult; +} + + SWIGEXPORT int SWIGSTDCALL CSharp_FreeSWITCHfNative_switch_channel_add_variable_var_check___(void * jarg1, char * jarg2, char * jarg3, int jarg4, int jarg5) { int jresult ; switch_channel_t *arg1 = (switch_channel_t *) 0 ; @@ -36556,6 +36804,22 @@ SWIGEXPORT int SWIGSTDCALL CSharp_FreeSWITCHfNative_switch_channel_get_variables } +SWIGEXPORT int SWIGSTDCALL CSharp_FreeSWITCHfNative_switch_channel_get_variables_prefix___(void * jarg1, char * jarg2, void * jarg3) { + int jresult ; + switch_channel_t *arg1 = (switch_channel_t *) 0 ; + char *arg2 = (char *) 0 ; + switch_event_t **arg3 = (switch_event_t **) 0 ; + switch_status_t result; + + arg1 = (switch_channel_t *)jarg1; + arg2 = (char *)jarg2; + arg3 = (switch_event_t **)jarg3; + result = (switch_status_t)switch_channel_get_variables_prefix(arg1,(char const *)arg2,arg3); + jresult = (int)result; + return jresult; +} + + SWIGEXPORT int SWIGSTDCALL CSharp_FreeSWITCHfNative_switch_channel_pass_callee_id___(void * jarg1, void * jarg2) { int jresult ; switch_channel_t *arg1 = (switch_channel_t *) 0 ; @@ -37620,6 +37884,20 @@ SWIGEXPORT int SWIGSTDCALL CSharp_FreeSWITCHfNative_switch_channel_execute_on___ } +SWIGEXPORT int SWIGSTDCALL CSharp_FreeSWITCHfNative_switch_channel_execute_on_value___(void * jarg1, char * jarg2) { + int jresult ; + switch_channel_t *arg1 = (switch_channel_t *) 0 ; + char *arg2 = (char *) 0 ; + switch_status_t result; + + arg1 = (switch_channel_t *)jarg1; + arg2 = (char *)jarg2; + result = (switch_status_t)switch_channel_execute_on_value(arg1,(char const *)arg2); + jresult = (int)result; + return jresult; +} + + SWIGEXPORT int SWIGSTDCALL CSharp_FreeSWITCHfNative_switch_channel_api_on___(void * jarg1, char * jarg2) { int jresult ; switch_channel_t *arg1 = (switch_channel_t *) 0 ; @@ -41909,6 +42187,28 @@ SWIGEXPORT int SWIGSTDCALL CSharp_FreeSWITCHfNative_switch_ivr_record_file___(vo } +SWIGEXPORT int SWIGSTDCALL CSharp_FreeSWITCHfNative_switch_ivr_record_file_event___(void * jarg1, void * jarg2, char * jarg3, void * jarg4, unsigned long jarg5, void * jarg6) { + int jresult ; + switch_core_session_t *arg1 = (switch_core_session_t *) 0 ; + switch_file_handle_t *arg2 = (switch_file_handle_t *) 0 ; + char *arg3 = (char *) 0 ; + switch_input_args_t *arg4 = (switch_input_args_t *) 0 ; + uint32_t arg5 ; + switch_event_t *arg6 = (switch_event_t *) 0 ; + switch_status_t result; + + arg1 = (switch_core_session_t *)jarg1; + arg2 = (switch_file_handle_t *)jarg2; + arg3 = (char *)jarg3; + arg4 = (switch_input_args_t *)jarg4; + arg5 = (uint32_t)jarg5; + arg6 = (switch_event_t *)jarg6; + result = (switch_status_t)switch_ivr_record_file_event(arg1,arg2,(char const *)arg3,arg4,arg5,arg6); + jresult = (int)result; + return jresult; +} + + SWIGEXPORT int SWIGSTDCALL CSharp_FreeSWITCHfNative_switch_play_and_get_digits___(void * jarg1, unsigned long jarg2, unsigned long jarg3, unsigned long jarg4, unsigned long jarg5, char * jarg6, char * jarg7, char * jarg8, char * jarg9, char * jarg10, unsigned long jarg11, char * jarg12, unsigned long jarg13, char * jarg14) { int jresult ; switch_core_session_t *arg1 = (switch_core_session_t *) 0 ; @@ -43529,6 +43829,22 @@ SWIGEXPORT int SWIGSTDCALL CSharp_FreeSWITCHfNative_switch_ivr_record_session_ma } +SWIGEXPORT int SWIGSTDCALL CSharp_FreeSWITCHfNative_switch_ivr_record_session_pause___(void * jarg1, char * jarg2, int jarg3) { + int jresult ; + switch_core_session_t *arg1 = (switch_core_session_t *) 0 ; + char *arg2 = (char *) 0 ; + switch_bool_t arg3 ; + switch_status_t result; + + arg1 = (switch_core_session_t *)jarg1; + arg2 = (char *)jarg2; + arg3 = (switch_bool_t)jarg3; + result = (switch_status_t)switch_ivr_record_session_pause(arg1,(char const *)arg2,arg3); + jresult = (int)result; + return jresult; +} + + SWIGEXPORT int SWIGSTDCALL CSharp_FreeSWITCHfNative_switch_ivr_stop_video_write_overlay_session___(void * jarg1) { int jresult ; switch_core_session_t *arg1 = (switch_core_session_t *) 0 ; @@ -43985,6 +44301,24 @@ SWIGEXPORT int SWIGSTDCALL CSharp_FreeSWITCHfNative_switch_ivr_orig_and_bridge__ } +SWIGEXPORT int SWIGSTDCALL CSharp_FreeSWITCHfNative_switch_ivr_send_prompt___(void * jarg1, char * jarg2, char * jarg3, char * jarg4) { + int jresult ; + switch_core_session_t *arg1 = (switch_core_session_t *) 0 ; + char *arg2 = (char *) 0 ; + char *arg3 = (char *) 0 ; + char *arg4 = (char *) 0 ; + switch_status_t result; + + arg1 = (switch_core_session_t *)jarg1; + arg2 = (char *)jarg2; + arg3 = (char *)jarg3; + arg4 = (char *)jarg4; + result = (switch_status_t)switch_ivr_send_prompt(arg1,(char const *)arg2,(char const *)arg3,(char const *)arg4); + jresult = (int)result; + return jresult; +} + + SWIGEXPORT int SWIGSTDCALL CSharp_FreeSWITCHfNative_switch_ivr_play_and_collect_input___(void * jarg1, char * jarg2, char * jarg3, char * jarg4, int jarg5, int jarg6, char * jarg7, unsigned long jarg8, void * jarg9, void * jarg10, char * jarg11, void * jarg12) { int jresult ; switch_core_session_t *arg1 = (switch_core_session_t *) 0 ; @@ -46422,6 +46756,50 @@ SWIGEXPORT void * SWIGSTDCALL CSharp_FreeSWITCHfNative_switch_log_node_t_tags_ge } +SWIGEXPORT void SWIGSTDCALL CSharp_FreeSWITCHfNative_switch_log_node_t_sequence_set___(void * jarg1, long long jarg2) { + switch_log_node_t *arg1 = (switch_log_node_t *) 0 ; + int64_t arg2 ; + + arg1 = (switch_log_node_t *)jarg1; + arg2 = (int64_t)jarg2; + if (arg1) (arg1)->sequence = arg2; +} + + +SWIGEXPORT long long SWIGSTDCALL CSharp_FreeSWITCHfNative_switch_log_node_t_sequence_get___(void * jarg1) { + long long jresult ; + switch_log_node_t *arg1 = (switch_log_node_t *) 0 ; + int64_t result; + + arg1 = (switch_log_node_t *)jarg1; + result = (int64_t) ((arg1)->sequence); + jresult = result; + return jresult; +} + + +SWIGEXPORT void SWIGSTDCALL CSharp_FreeSWITCHfNative_switch_log_node_t_meta_set___(void * jarg1, void * jarg2) { + switch_log_node_t *arg1 = (switch_log_node_t *) 0 ; + cJSON *arg2 = (cJSON *) 0 ; + + arg1 = (switch_log_node_t *)jarg1; + arg2 = (cJSON *)jarg2; + if (arg1) (arg1)->meta = arg2; +} + + +SWIGEXPORT void * SWIGSTDCALL CSharp_FreeSWITCHfNative_switch_log_node_t_meta_get___(void * jarg1) { + void * jresult ; + switch_log_node_t *arg1 = (switch_log_node_t *) 0 ; + cJSON *result = 0 ; + + arg1 = (switch_log_node_t *)jarg1; + result = (cJSON *) ((arg1)->meta); + jresult = (void *)result; + return jresult; +} + + SWIGEXPORT void * SWIGSTDCALL CSharp_FreeSWITCHfNative_new_switch_log_node_t___() { void * jresult ; switch_log_node_t *result = 0 ; @@ -46831,6 +47209,28 @@ SWIGEXPORT double SWIGSTDCALL CSharp_FreeSWITCHfNative_switch_log_json_format_t_ } +SWIGEXPORT void SWIGSTDCALL CSharp_FreeSWITCHfNative_switch_log_json_format_t_sequence_set___(void * jarg1, void * jarg2) { + switch_log_json_format_t *arg1 = (switch_log_json_format_t *) 0 ; + switch_log_json_format_item_t *arg2 = (switch_log_json_format_item_t *) 0 ; + + arg1 = (switch_log_json_format_t *)jarg1; + arg2 = (switch_log_json_format_item_t *)jarg2; + if (arg1) (arg1)->sequence = *arg2; +} + + +SWIGEXPORT void * SWIGSTDCALL CSharp_FreeSWITCHfNative_switch_log_json_format_t_sequence_get___(void * jarg1) { + void * jresult ; + switch_log_json_format_t *arg1 = (switch_log_json_format_t *) 0 ; + switch_log_json_format_item_t *result = 0 ; + + arg1 = (switch_log_json_format_t *)jarg1; + result = (switch_log_json_format_item_t *)& ((arg1)->sequence); + jresult = (void *)result; + return jresult; +} + + SWIGEXPORT void * SWIGSTDCALL CSharp_FreeSWITCHfNative_new_switch_log_json_format_t___() { void * jresult ; switch_log_json_format_t *result = 0 ; @@ -47301,6 +47701,64 @@ SWIGEXPORT unsigned long SWIGSTDCALL CSharp_FreeSWITCHfNative_switch_xml_refs_ge } +SWIGEXPORT void SWIGSTDCALL CSharp_FreeSWITCHfNative_switch_xml_open_set___(void * jarg1, char * jarg2) { + switch_xml *arg1 = (switch_xml *) 0 ; + char *arg2 = (char *) 0 ; + + arg1 = (switch_xml *)jarg1; + arg2 = (char *)jarg2; + { + if (arg2) { + arg1->open = (char const *) (new char[strlen((const char *)arg2)+1]); + strcpy((char *)arg1->open, (const char *)arg2); + } else { + arg1->open = 0; + } + } +} + + +SWIGEXPORT char * SWIGSTDCALL CSharp_FreeSWITCHfNative_switch_xml_open_get___(void * jarg1) { + char * jresult ; + switch_xml *arg1 = (switch_xml *) 0 ; + char *result = 0 ; + + arg1 = (switch_xml *)jarg1; + result = (char *) ((arg1)->open); + jresult = SWIG_csharp_string_callback((const char *)result); + return jresult; +} + + +SWIGEXPORT void SWIGSTDCALL CSharp_FreeSWITCHfNative_switch_xml_close_set___(void * jarg1, char * jarg2) { + switch_xml *arg1 = (switch_xml *) 0 ; + char *arg2 = (char *) 0 ; + + arg1 = (switch_xml *)jarg1; + arg2 = (char *)jarg2; + { + if (arg2) { + arg1->close = (char const *) (new char[strlen((const char *)arg2)+1]); + strcpy((char *)arg1->close, (const char *)arg2); + } else { + arg1->close = 0; + } + } +} + + +SWIGEXPORT char * SWIGSTDCALL CSharp_FreeSWITCHfNative_switch_xml_close_get___(void * jarg1) { + char * jresult ; + switch_xml *arg1 = (switch_xml *) 0 ; + char *result = 0 ; + + arg1 = (switch_xml *)jarg1; + result = (char *) ((arg1)->close); + jresult = SWIG_csharp_string_callback((const char *)result); + return jresult; +} + + SWIGEXPORT void * SWIGSTDCALL CSharp_FreeSWITCHfNative_new_switch_xml___() { void * jresult ; switch_xml *result = 0 ; diff --git a/src/mod/languages/mod_managed/managed/swig.cs b/src/mod/languages/mod_managed/managed/swig.cs index 025c93a74d..901476e9f1 100644 --- a/src/mod/languages/mod_managed/managed/swig.cs +++ b/src/mod/languages/mod_managed/managed/swig.cs @@ -7843,6 +7843,17 @@ public class freeswitch { } } + public static SWIGTYPE_p_switch_core_session switch_core_session_type_check(SWIGTYPE_p_switch_core_session session) { + global::System.IntPtr cPtr = freeswitchPINVOKE.switch_core_session_type_check(SWIGTYPE_p_switch_core_session.getCPtr(session)); + SWIGTYPE_p_switch_core_session ret = (cPtr == global::System.IntPtr.Zero) ? null : new SWIGTYPE_p_switch_core_session(cPtr, false); + return ret; + } + + public static string switch_const_char_type_check(string str) { + string ret = freeswitchPINVOKE.switch_const_char_type_check(str); + return ret; + } + public static int switch_core_db_close(SWIGTYPE_p_sqlite3 db) { int ret = freeswitchPINVOKE.switch_core_db_close(SWIGTYPE_p_sqlite3.getCPtr(db)); return ret; @@ -8032,11 +8043,6 @@ else return ret; } - public static string switch_must_strdup(string _s) { - string ret = freeswitchPINVOKE.switch_must_strdup(_s); - return ret; - } - public static void switch_core_screen_size(SWIGTYPE_p_int x, SWIGTYPE_p_int y) { freeswitchPINVOKE.switch_core_screen_size(SWIGTYPE_p_int.getCPtr(x), SWIGTYPE_p_int.getCPtr(y)); } @@ -8489,6 +8495,11 @@ else return ret; } + public static switch_status_t switch_core_session_set_external_id(SWIGTYPE_p_switch_core_session session, string use_external_id) { + switch_status_t ret = (switch_status_t)freeswitchPINVOKE.switch_core_session_set_external_id(SWIGTYPE_p_switch_core_session.getCPtr(session), use_external_id); + return ret; + } + public static void switch_core_session_perform_destroy(SWIGTYPE_p_p_switch_core_session session, string file, string func, int line) { freeswitchPINVOKE.switch_core_session_perform_destroy(SWIGTYPE_p_p_switch_core_session.getCPtr(session), file, func, line); } @@ -8546,6 +8557,11 @@ else return ret; } + public static switch_status_t switch_thread_pool_wait(switch_thread_data_t td, int ms) { + switch_status_t ret = (switch_status_t)freeswitchPINVOKE.switch_thread_pool_wait(switch_thread_data_t.getCPtr(td), ms); + return ret; + } + public static SWIGTYPE_p_switch_channel switch_core_session_get_channel(SWIGTYPE_p_switch_core_session session) { global::System.IntPtr cPtr = freeswitchPINVOKE.switch_core_session_get_channel(SWIGTYPE_p_switch_core_session.getCPtr(session)); SWIGTYPE_p_switch_channel ret = (cPtr == global::System.IntPtr.Zero) ? null : new SWIGTYPE_p_switch_channel(cPtr, false); @@ -8572,6 +8588,11 @@ else return ret; } + public static string switch_core_session_get_external_id(SWIGTYPE_p_switch_core_session session) { + string ret = freeswitchPINVOKE.switch_core_session_get_external_id(SWIGTYPE_p_switch_core_session.getCPtr(session)); + return ret; + } + public static switch_status_t switch_core_session_set_loglevel(SWIGTYPE_p_switch_core_session session, switch_log_level_t loglevel) { switch_status_t ret = (switch_status_t)freeswitchPINVOKE.switch_core_session_set_loglevel(SWIGTYPE_p_switch_core_session.getCPtr(session), (int)loglevel); return ret; @@ -9010,16 +9031,37 @@ else return ret; } + public static switch_status_t switch_core_hash_insert_pointer(SWIGTYPE_p_switch_hashtable hash, SWIGTYPE_p_void data) { + switch_status_t ret = (switch_status_t)freeswitchPINVOKE.switch_core_hash_insert_pointer(SWIGTYPE_p_switch_hashtable.getCPtr(hash), SWIGTYPE_p_void.getCPtr(data)); + return ret; + } + public static switch_status_t switch_core_hash_insert_auto_free(SWIGTYPE_p_switch_hashtable hash, string key, SWIGTYPE_p_void data) { switch_status_t ret = (switch_status_t)freeswitchPINVOKE.switch_core_hash_insert_auto_free(SWIGTYPE_p_switch_hashtable.getCPtr(hash), key, SWIGTYPE_p_void.getCPtr(data)); return ret; } + public static switch_status_t switch_core_hash_insert_dup_auto_free(SWIGTYPE_p_switch_hashtable hash, string key, string str) { + switch_status_t ret = (switch_status_t)freeswitchPINVOKE.switch_core_hash_insert_dup_auto_free(SWIGTYPE_p_switch_hashtable.getCPtr(hash), key, str); + return ret; + } + public static switch_status_t switch_core_hash_insert_destructor(SWIGTYPE_p_switch_hashtable hash, string key, SWIGTYPE_p_void data, SWIGTYPE_p_f_p_void__void destructor) { switch_status_t ret = (switch_status_t)freeswitchPINVOKE.switch_core_hash_insert_destructor(SWIGTYPE_p_switch_hashtable.getCPtr(hash), key, SWIGTYPE_p_void.getCPtr(data), SWIGTYPE_p_f_p_void__void.getCPtr(destructor)); return ret; } + public static SWIGTYPE_p_void switch_core_hash_insert_alloc_destructor(SWIGTYPE_p_switch_hashtable hash, string key, uint size, SWIGTYPE_p_f_p_void__void destructor) { + global::System.IntPtr cPtr = freeswitchPINVOKE.switch_core_hash_insert_alloc_destructor(SWIGTYPE_p_switch_hashtable.getCPtr(hash), key, size, SWIGTYPE_p_f_p_void__void.getCPtr(destructor)); + SWIGTYPE_p_void ret = (cPtr == global::System.IntPtr.Zero) ? null : new SWIGTYPE_p_void(cPtr, false); + return ret; + } + + public static switch_status_t switch_core_hash_insert_dup_destructor(SWIGTYPE_p_switch_hashtable hash, string key, string str, SWIGTYPE_p_f_p_void__void destructor) { + switch_status_t ret = (switch_status_t)freeswitchPINVOKE.switch_core_hash_insert_dup_destructor(SWIGTYPE_p_switch_hashtable.getCPtr(hash), key, str, SWIGTYPE_p_f_p_void__void.getCPtr(destructor)); + return ret; + } + public static switch_status_t switch_core_hash_insert_locked(SWIGTYPE_p_switch_hashtable hash, string key, SWIGTYPE_p_void data, SWIGTYPE_p_switch_mutex_t mutex) { switch_status_t ret = (switch_status_t)freeswitchPINVOKE.switch_core_hash_insert_locked(SWIGTYPE_p_switch_hashtable.getCPtr(hash), key, SWIGTYPE_p_void.getCPtr(data), SWIGTYPE_p_switch_mutex_t.getCPtr(mutex)); return ret; @@ -10952,8 +10994,8 @@ else return ret; } - public static int switch_cmp_addr(SWIGTYPE_p_switch_sockaddr_t sa1, SWIGTYPE_p_switch_sockaddr_t sa2) { - int ret = freeswitchPINVOKE.switch_cmp_addr(SWIGTYPE_p_switch_sockaddr_t.getCPtr(sa1), SWIGTYPE_p_switch_sockaddr_t.getCPtr(sa2)); + public static int switch_cmp_addr(SWIGTYPE_p_switch_sockaddr_t sa1, SWIGTYPE_p_switch_sockaddr_t sa2, switch_bool_t ip_only) { + int ret = freeswitchPINVOKE.switch_cmp_addr(SWIGTYPE_p_switch_sockaddr_t.getCPtr(sa1), SWIGTYPE_p_switch_sockaddr_t.getCPtr(sa2), (int)ip_only); return ret; } @@ -11028,6 +11070,16 @@ else return ret; } + public static int switch_safe_atol(string nptr, int dft) { + int ret = freeswitchPINVOKE.switch_safe_atol(nptr, dft); + return ret; + } + + public static long switch_safe_atoll(string nptr, long dft) { + long ret = freeswitchPINVOKE.switch_safe_atoll(nptr, dft); + return ret; + } + public static string switch_safe_strdup(string it) { string ret = freeswitchPINVOKE.switch_safe_strdup(it); return ret; @@ -11244,6 +11296,11 @@ else return ret; } + public static int switch_filecmp(string a, string b) { + int ret = freeswitchPINVOKE.switch_filecmp(a, b); + return ret; + } + public static string switch_parse_audio_col(switch_audio_col_t col) { string ret = freeswitchPINVOKE.switch_parse_audio_col((int)col); return ret; @@ -11513,6 +11570,16 @@ else return ret; } + public static string switch_must_strdup(string _s) { + string ret = freeswitchPINVOKE.switch_must_strdup(_s); + return ret; + } + + public static string switch_memory_usage_stream(switch_stream_handle stream) { + string ret = freeswitchPINVOKE.switch_memory_usage_stream(switch_stream_handle.getCPtr(stream)); + return ret; + } + public static switch_caller_extension switch_caller_extension_new(SWIGTYPE_p_switch_core_session session, string extension_name, string extension_number) { global::System.IntPtr cPtr = freeswitchPINVOKE.switch_caller_extension_new(SWIGTYPE_p_switch_core_session.getCPtr(session), extension_name, extension_number); switch_caller_extension ret = (cPtr == global::System.IntPtr.Zero) ? null : new switch_caller_extension(cPtr, false); @@ -11739,6 +11806,11 @@ else return ret; } + public static switch_status_t switch_channel_set_variable_strip_quotes_var_check(SWIGTYPE_p_switch_channel channel, string varname, string value, switch_bool_t var_check) { + switch_status_t ret = (switch_status_t)freeswitchPINVOKE.switch_channel_set_variable_strip_quotes_var_check(SWIGTYPE_p_switch_channel.getCPtr(channel), varname, value, (int)var_check); + return ret; + } + public static switch_status_t switch_channel_add_variable_var_check(SWIGTYPE_p_switch_channel channel, string varname, string value, switch_bool_t var_check, switch_stack_t stack) { switch_status_t ret = (switch_status_t)freeswitchPINVOKE.switch_channel_add_variable_var_check(SWIGTYPE_p_switch_channel.getCPtr(channel), varname, value, (int)var_check, (int)stack); return ret; @@ -11817,6 +11889,11 @@ else return ret; } + public static switch_status_t switch_channel_get_variables_prefix(SWIGTYPE_p_switch_channel channel, string prefix, SWIGTYPE_p_p_switch_event arg2) { + switch_status_t ret = (switch_status_t)freeswitchPINVOKE.switch_channel_get_variables_prefix(SWIGTYPE_p_switch_channel.getCPtr(channel), prefix, SWIGTYPE_p_p_switch_event.getCPtr(arg2)); + return ret; + } + public static switch_status_t switch_channel_pass_callee_id(SWIGTYPE_p_switch_channel channel, SWIGTYPE_p_switch_channel other_channel) { switch_status_t ret = (switch_status_t)freeswitchPINVOKE.switch_channel_pass_callee_id(SWIGTYPE_p_switch_channel.getCPtr(channel), SWIGTYPE_p_switch_channel.getCPtr(other_channel)); return ret; @@ -12208,6 +12285,11 @@ else return ret; } + public static switch_status_t switch_channel_execute_on_value(SWIGTYPE_p_switch_channel channel, string variable_value) { + switch_status_t ret = (switch_status_t)freeswitchPINVOKE.switch_channel_execute_on_value(SWIGTYPE_p_switch_channel.getCPtr(channel), variable_value); + return ret; + } + public static switch_status_t switch_channel_api_on(SWIGTYPE_p_switch_channel channel, string variable_prefix) { switch_status_t ret = (switch_status_t)freeswitchPINVOKE.switch_channel_api_on(SWIGTYPE_p_switch_channel.getCPtr(channel), variable_prefix); return ret; @@ -13152,6 +13234,11 @@ else return ret; } + public static switch_status_t switch_ivr_record_file_event(SWIGTYPE_p_switch_core_session session, switch_file_handle fh, string file, switch_input_args_t args, uint limit, switch_event vars) { + switch_status_t ret = (switch_status_t)freeswitchPINVOKE.switch_ivr_record_file_event(SWIGTYPE_p_switch_core_session.getCPtr(session), switch_file_handle.getCPtr(fh), file, switch_input_args_t.getCPtr(args), limit, switch_event.getCPtr(vars)); + return ret; + } + public static switch_status_t switch_play_and_get_digits(SWIGTYPE_p_switch_core_session session, uint min_digits, uint max_digits, uint max_tries, uint timeout, string valid_terminators, string audio_file, string bad_input_audio_file, string var_name, string digit_buffer, uint digit_buffer_length, string digits_regex, uint digit_timeout, string transfer_on_failure) { switch_status_t ret = (switch_status_t)freeswitchPINVOKE.switch_play_and_get_digits(SWIGTYPE_p_switch_core_session.getCPtr(session), min_digits, max_digits, max_tries, timeout, valid_terminators, audio_file, bad_input_audio_file, var_name, digit_buffer, digit_buffer_length, digits_regex, digit_timeout, transfer_on_failure); return ret; @@ -13642,6 +13729,11 @@ else return ret; } + public static switch_status_t switch_ivr_record_session_pause(SWIGTYPE_p_switch_core_session session, string file, switch_bool_t on) { + switch_status_t ret = (switch_status_t)freeswitchPINVOKE.switch_ivr_record_session_pause(SWIGTYPE_p_switch_core_session.getCPtr(session), file, (int)on); + return ret; + } + public static switch_status_t switch_ivr_stop_video_write_overlay_session(SWIGTYPE_p_switch_core_session session) { switch_status_t ret = (switch_status_t)freeswitchPINVOKE.switch_ivr_stop_video_write_overlay_session(SWIGTYPE_p_switch_core_session.getCPtr(session)); return ret; @@ -13801,6 +13893,11 @@ else return ret; } + public static switch_status_t switch_ivr_send_prompt(SWIGTYPE_p_switch_core_session session, string type, string text, string regex) { + switch_status_t ret = (switch_status_t)freeswitchPINVOKE.switch_ivr_send_prompt(SWIGTYPE_p_switch_core_session.getCPtr(session), type, text, regex); + return ret; + } + public static switch_status_t switch_ivr_play_and_collect_input(SWIGTYPE_p_switch_core_session session, string prompt, string recognizer_mod_name, string recognizer_grammar, int min_digits, int max_digits, string terminators, uint digit_timeout, SWIGTYPE_p_p_cJSON recognition_result, ref string digits_collected, string terminator_collected, switch_input_args_t args) { switch_status_t ret = (switch_status_t)freeswitchPINVOKE.switch_ivr_play_and_collect_input(SWIGTYPE_p_switch_core_session.getCPtr(session), prompt, recognizer_mod_name, recognizer_grammar, min_digits, max_digits, terminators, digit_timeout, SWIGTYPE_p_p_cJSON.getCPtr(recognition_result), ref digits_collected, terminator_collected, switch_input_args_t.getCPtr(args)); return ret; @@ -16845,6 +16942,12 @@ class freeswitchPINVOKE { [global::System.Runtime.InteropServices.DllImport("mod_managed", EntryPoint="CSharp_FreeSWITCHfNative_delete_switch_t38_options_t___")] public static extern void delete_switch_t38_options_t(global::System.Runtime.InteropServices.HandleRef jarg1); + [global::System.Runtime.InteropServices.DllImport("mod_managed", EntryPoint="CSharp_FreeSWITCHfNative_switch_core_session_type_check___")] + public static extern global::System.IntPtr switch_core_session_type_check(global::System.Runtime.InteropServices.HandleRef jarg1); + + [global::System.Runtime.InteropServices.DllImport("mod_managed", EntryPoint="CSharp_FreeSWITCHfNative_switch_const_char_type_check___")] + public static extern string switch_const_char_type_check(string jarg1); + [global::System.Runtime.InteropServices.DllImport("mod_managed", EntryPoint="CSharp_FreeSWITCHfNative_switch_vid_params_t_width_set___")] public static extern void switch_vid_params_t_width_set(global::System.Runtime.InteropServices.HandleRef jarg1, uint jarg2); @@ -17352,6 +17455,12 @@ class freeswitchPINVOKE { [global::System.Runtime.InteropServices.DllImport("mod_managed", EntryPoint="CSharp_FreeSWITCHfNative_switch_mm_t_source_fps_get___")] public static extern float switch_mm_t_source_fps_get(global::System.Runtime.InteropServices.HandleRef jarg1); + [global::System.Runtime.InteropServices.DllImport("mod_managed", EntryPoint="CSharp_FreeSWITCHfNative_switch_mm_t_source_kps_set___")] + public static extern void switch_mm_t_source_kps_set(global::System.Runtime.InteropServices.HandleRef jarg1, int jarg2); + + [global::System.Runtime.InteropServices.DllImport("mod_managed", EntryPoint="CSharp_FreeSWITCHfNative_switch_mm_t_source_kps_get___")] + public static extern int switch_mm_t_source_kps_get(global::System.Runtime.InteropServices.HandleRef jarg1); + [global::System.Runtime.InteropServices.DllImport("mod_managed", EntryPoint="CSharp_FreeSWITCHfNative_switch_mm_t_vbuf_set___")] public static extern void switch_mm_t_vbuf_set(global::System.Runtime.InteropServices.HandleRef jarg1, int jarg2); @@ -17841,6 +17950,12 @@ class freeswitchPINVOKE { [global::System.Runtime.InteropServices.DllImport("mod_managed", EntryPoint="CSharp_FreeSWITCHfNative_switch_thread_data_t_alloc_get___")] public static extern int switch_thread_data_t_alloc_get(global::System.Runtime.InteropServices.HandleRef jarg1); + [global::System.Runtime.InteropServices.DllImport("mod_managed", EntryPoint="CSharp_FreeSWITCHfNative_switch_thread_data_t_running_set___")] + public static extern void switch_thread_data_t_running_set(global::System.Runtime.InteropServices.HandleRef jarg1, int jarg2); + + [global::System.Runtime.InteropServices.DllImport("mod_managed", EntryPoint="CSharp_FreeSWITCHfNative_switch_thread_data_t_running_get___")] + public static extern int switch_thread_data_t_running_get(global::System.Runtime.InteropServices.HandleRef jarg1); + [global::System.Runtime.InteropServices.DllImport("mod_managed", EntryPoint="CSharp_FreeSWITCHfNative_switch_thread_data_t_pool_set___")] public static extern void switch_thread_data_t_pool_set(global::System.Runtime.InteropServices.HandleRef jarg1, global::System.Runtime.InteropServices.HandleRef jarg2); @@ -18423,9 +18538,6 @@ class freeswitchPINVOKE { [global::System.Runtime.InteropServices.DllImport("mod_managed", EntryPoint="CSharp_FreeSWITCHfNative_switch_must_realloc___")] public static extern global::System.IntPtr switch_must_realloc(global::System.Runtime.InteropServices.HandleRef jarg1, uint jarg2); - [global::System.Runtime.InteropServices.DllImport("mod_managed", EntryPoint="CSharp_FreeSWITCHfNative_switch_must_strdup___")] - public static extern string switch_must_strdup(string jarg1); - [global::System.Runtime.InteropServices.DllImport("mod_managed", EntryPoint="CSharp_FreeSWITCHfNative_switch_core_screen_size___")] public static extern void switch_core_screen_size(global::System.Runtime.InteropServices.HandleRef jarg1, global::System.Runtime.InteropServices.HandleRef jarg2); @@ -18690,6 +18802,9 @@ class freeswitchPINVOKE { [global::System.Runtime.InteropServices.DllImport("mod_managed", EntryPoint="CSharp_FreeSWITCHfNative_switch_core_session_set_uuid___")] public static extern int switch_core_session_set_uuid(global::System.Runtime.InteropServices.HandleRef jarg1, string jarg2); + [global::System.Runtime.InteropServices.DllImport("mod_managed", EntryPoint="CSharp_FreeSWITCHfNative_switch_core_session_set_external_id___")] + public static extern int switch_core_session_set_external_id(global::System.Runtime.InteropServices.HandleRef jarg1, string jarg2); + [global::System.Runtime.InteropServices.DllImport("mod_managed", EntryPoint="CSharp_FreeSWITCHfNative_switch_core_session_perform_destroy___")] public static extern void switch_core_session_perform_destroy(global::System.Runtime.InteropServices.HandleRef jarg1, string jarg2, string jarg3, int jarg4); @@ -18726,6 +18841,9 @@ class freeswitchPINVOKE { [global::System.Runtime.InteropServices.DllImport("mod_managed", EntryPoint="CSharp_FreeSWITCHfNative_switch_core_session_thread_pool_launch___")] public static extern int switch_core_session_thread_pool_launch(global::System.Runtime.InteropServices.HandleRef jarg1); + [global::System.Runtime.InteropServices.DllImport("mod_managed", EntryPoint="CSharp_FreeSWITCHfNative_switch_thread_pool_wait___")] + public static extern int switch_thread_pool_wait(global::System.Runtime.InteropServices.HandleRef jarg1, int jarg2); + [global::System.Runtime.InteropServices.DllImport("mod_managed", EntryPoint="CSharp_FreeSWITCHfNative_switch_core_session_get_channel___")] public static extern global::System.IntPtr switch_core_session_get_channel(global::System.Runtime.InteropServices.HandleRef jarg1); @@ -18741,6 +18859,9 @@ class freeswitchPINVOKE { [global::System.Runtime.InteropServices.DllImport("mod_managed", EntryPoint="CSharp_FreeSWITCHfNative_switch_core_session_get_uuid___")] public static extern string switch_core_session_get_uuid(global::System.Runtime.InteropServices.HandleRef jarg1); + [global::System.Runtime.InteropServices.DllImport("mod_managed", EntryPoint="CSharp_FreeSWITCHfNative_switch_core_session_get_external_id___")] + public static extern string switch_core_session_get_external_id(global::System.Runtime.InteropServices.HandleRef jarg1); + [global::System.Runtime.InteropServices.DllImport("mod_managed", EntryPoint="CSharp_FreeSWITCHfNative_switch_core_session_set_loglevel___")] public static extern int switch_core_session_set_loglevel(global::System.Runtime.InteropServices.HandleRef jarg1, int jarg2); @@ -19008,12 +19129,24 @@ class freeswitchPINVOKE { [global::System.Runtime.InteropServices.DllImport("mod_managed", EntryPoint="CSharp_FreeSWITCHfNative_switch_core_hash_destroy___")] public static extern int switch_core_hash_destroy(global::System.Runtime.InteropServices.HandleRef jarg1); + [global::System.Runtime.InteropServices.DllImport("mod_managed", EntryPoint="CSharp_FreeSWITCHfNative_switch_core_hash_insert_pointer___")] + public static extern int switch_core_hash_insert_pointer(global::System.Runtime.InteropServices.HandleRef jarg1, global::System.Runtime.InteropServices.HandleRef jarg2); + [global::System.Runtime.InteropServices.DllImport("mod_managed", EntryPoint="CSharp_FreeSWITCHfNative_switch_core_hash_insert_auto_free___")] public static extern int switch_core_hash_insert_auto_free(global::System.Runtime.InteropServices.HandleRef jarg1, string jarg2, global::System.Runtime.InteropServices.HandleRef jarg3); + [global::System.Runtime.InteropServices.DllImport("mod_managed", EntryPoint="CSharp_FreeSWITCHfNative_switch_core_hash_insert_dup_auto_free___")] + public static extern int switch_core_hash_insert_dup_auto_free(global::System.Runtime.InteropServices.HandleRef jarg1, string jarg2, string jarg3); + [global::System.Runtime.InteropServices.DllImport("mod_managed", EntryPoint="CSharp_FreeSWITCHfNative_switch_core_hash_insert_destructor___")] public static extern int switch_core_hash_insert_destructor(global::System.Runtime.InteropServices.HandleRef jarg1, string jarg2, global::System.Runtime.InteropServices.HandleRef jarg3, global::System.Runtime.InteropServices.HandleRef jarg4); + [global::System.Runtime.InteropServices.DllImport("mod_managed", EntryPoint="CSharp_FreeSWITCHfNative_switch_core_hash_insert_alloc_destructor___")] + public static extern global::System.IntPtr switch_core_hash_insert_alloc_destructor(global::System.Runtime.InteropServices.HandleRef jarg1, string jarg2, uint jarg3, global::System.Runtime.InteropServices.HandleRef jarg4); + + [global::System.Runtime.InteropServices.DllImport("mod_managed", EntryPoint="CSharp_FreeSWITCHfNative_switch_core_hash_insert_dup_destructor___")] + public static extern int switch_core_hash_insert_dup_destructor(global::System.Runtime.InteropServices.HandleRef jarg1, string jarg2, string jarg3, global::System.Runtime.InteropServices.HandleRef jarg4); + [global::System.Runtime.InteropServices.DllImport("mod_managed", EntryPoint="CSharp_FreeSWITCHfNative_switch_core_hash_insert_locked___")] public static extern int switch_core_hash_insert_locked(global::System.Runtime.InteropServices.HandleRef jarg1, string jarg2, global::System.Runtime.InteropServices.HandleRef jarg3, global::System.Runtime.InteropServices.HandleRef jarg4); @@ -20482,7 +20615,7 @@ class freeswitchPINVOKE { public static extern int get_addr_int(global::System.Runtime.InteropServices.HandleRef jarg1); [global::System.Runtime.InteropServices.DllImport("mod_managed", EntryPoint="CSharp_FreeSWITCHfNative_switch_cmp_addr___")] - public static extern int switch_cmp_addr(global::System.Runtime.InteropServices.HandleRef jarg1, global::System.Runtime.InteropServices.HandleRef jarg2); + public static extern int switch_cmp_addr(global::System.Runtime.InteropServices.HandleRef jarg1, global::System.Runtime.InteropServices.HandleRef jarg2, int jarg3); [global::System.Runtime.InteropServices.DllImport("mod_managed", EntryPoint="CSharp_FreeSWITCHfNative_switch_cp_addr___")] public static extern int switch_cp_addr(global::System.Runtime.InteropServices.HandleRef jarg1, global::System.Runtime.InteropServices.HandleRef jarg2); @@ -20526,6 +20659,12 @@ class freeswitchPINVOKE { [global::System.Runtime.InteropServices.DllImport("mod_managed", EntryPoint="CSharp_FreeSWITCHfNative_switch_safe_atoi___")] public static extern int switch_safe_atoi(string jarg1, int jarg2); + [global::System.Runtime.InteropServices.DllImport("mod_managed", EntryPoint="CSharp_FreeSWITCHfNative_switch_safe_atol___")] + public static extern int switch_safe_atol(string jarg1, int jarg2); + + [global::System.Runtime.InteropServices.DllImport("mod_managed", EntryPoint="CSharp_FreeSWITCHfNative_switch_safe_atoll___")] + public static extern long switch_safe_atoll(string jarg1, long jarg2); + [global::System.Runtime.InteropServices.DllImport("mod_managed", EntryPoint="CSharp_FreeSWITCHfNative_switch_safe_strdup___")] public static extern string switch_safe_strdup(string jarg1); @@ -20655,6 +20794,9 @@ class freeswitchPINVOKE { [global::System.Runtime.InteropServices.DllImport("mod_managed", EntryPoint="CSharp_FreeSWITCHfNative_switch_is_file_path___")] public static extern int switch_is_file_path(string jarg1); + [global::System.Runtime.InteropServices.DllImport("mod_managed", EntryPoint="CSharp_FreeSWITCHfNative_switch_filecmp___")] + public static extern int switch_filecmp(string jarg1, string jarg2); + [global::System.Runtime.InteropServices.DllImport("mod_managed", EntryPoint="CSharp_FreeSWITCHfNative_switch_parse_audio_col___")] public static extern string switch_parse_audio_col(int jarg1); @@ -20934,6 +21076,12 @@ class freeswitchPINVOKE { [global::System.Runtime.InteropServices.DllImport("mod_managed", EntryPoint="CSharp_FreeSWITCHfNative_switch_digest_string___")] public static extern int switch_digest_string(string jarg1, ref string jarg2, global::System.Runtime.InteropServices.HandleRef jarg3, global::System.Runtime.InteropServices.HandleRef jarg4, global::System.Runtime.InteropServices.HandleRef jarg5); + [global::System.Runtime.InteropServices.DllImport("mod_managed", EntryPoint="CSharp_FreeSWITCHfNative_switch_must_strdup___")] + public static extern string switch_must_strdup(string jarg1); + + [global::System.Runtime.InteropServices.DllImport("mod_managed", EntryPoint="CSharp_FreeSWITCHfNative_switch_memory_usage_stream___")] + public static extern string switch_memory_usage_stream(global::System.Runtime.InteropServices.HandleRef jarg1); + [global::System.Runtime.InteropServices.DllImport("mod_managed", EntryPoint="CSharp_FreeSWITCHfNative_profile_node_t_var_set___")] public static extern void profile_node_t_var_set(global::System.Runtime.InteropServices.HandleRef jarg1, string jarg2); @@ -24288,6 +24436,9 @@ class freeswitchPINVOKE { [global::System.Runtime.InteropServices.DllImport("mod_managed", EntryPoint="CSharp_FreeSWITCHfNative_switch_channel_set_variable_var_check___")] public static extern int switch_channel_set_variable_var_check(global::System.Runtime.InteropServices.HandleRef jarg1, string jarg2, string jarg3, int jarg4); + [global::System.Runtime.InteropServices.DllImport("mod_managed", EntryPoint="CSharp_FreeSWITCHfNative_switch_channel_set_variable_strip_quotes_var_check___")] + public static extern int switch_channel_set_variable_strip_quotes_var_check(global::System.Runtime.InteropServices.HandleRef jarg1, string jarg2, string jarg3, int jarg4); + [global::System.Runtime.InteropServices.DllImport("mod_managed", EntryPoint="CSharp_FreeSWITCHfNative_switch_channel_add_variable_var_check___")] public static extern int switch_channel_add_variable_var_check(global::System.Runtime.InteropServices.HandleRef jarg1, string jarg2, string jarg3, int jarg4, int jarg5); @@ -24336,6 +24487,9 @@ class freeswitchPINVOKE { [global::System.Runtime.InteropServices.DllImport("mod_managed", EntryPoint="CSharp_FreeSWITCHfNative_switch_channel_get_variables___")] public static extern int switch_channel_get_variables(global::System.Runtime.InteropServices.HandleRef jarg1, global::System.Runtime.InteropServices.HandleRef jarg2); + [global::System.Runtime.InteropServices.DllImport("mod_managed", EntryPoint="CSharp_FreeSWITCHfNative_switch_channel_get_variables_prefix___")] + public static extern int switch_channel_get_variables_prefix(global::System.Runtime.InteropServices.HandleRef jarg1, string jarg2, global::System.Runtime.InteropServices.HandleRef jarg3); + [global::System.Runtime.InteropServices.DllImport("mod_managed", EntryPoint="CSharp_FreeSWITCHfNative_switch_channel_pass_callee_id___")] public static extern int switch_channel_pass_callee_id(global::System.Runtime.InteropServices.HandleRef jarg1, global::System.Runtime.InteropServices.HandleRef jarg2); @@ -24585,6 +24739,9 @@ class freeswitchPINVOKE { [global::System.Runtime.InteropServices.DllImport("mod_managed", EntryPoint="CSharp_FreeSWITCHfNative_switch_channel_execute_on___")] public static extern int switch_channel_execute_on(global::System.Runtime.InteropServices.HandleRef jarg1, string jarg2); + [global::System.Runtime.InteropServices.DllImport("mod_managed", EntryPoint="CSharp_FreeSWITCHfNative_switch_channel_execute_on_value___")] + public static extern int switch_channel_execute_on_value(global::System.Runtime.InteropServices.HandleRef jarg1, string jarg2); + [global::System.Runtime.InteropServices.DllImport("mod_managed", EntryPoint="CSharp_FreeSWITCHfNative_switch_channel_api_on___")] public static extern int switch_channel_api_on(global::System.Runtime.InteropServices.HandleRef jarg1, string jarg2); @@ -25521,6 +25678,9 @@ class freeswitchPINVOKE { [global::System.Runtime.InteropServices.DllImport("mod_managed", EntryPoint="CSharp_FreeSWITCHfNative_switch_ivr_record_file___")] public static extern int switch_ivr_record_file(global::System.Runtime.InteropServices.HandleRef jarg1, global::System.Runtime.InteropServices.HandleRef jarg2, string jarg3, global::System.Runtime.InteropServices.HandleRef jarg4, uint jarg5); + [global::System.Runtime.InteropServices.DllImport("mod_managed", EntryPoint="CSharp_FreeSWITCHfNative_switch_ivr_record_file_event___")] + public static extern int switch_ivr_record_file_event(global::System.Runtime.InteropServices.HandleRef jarg1, global::System.Runtime.InteropServices.HandleRef jarg2, string jarg3, global::System.Runtime.InteropServices.HandleRef jarg4, uint jarg5, global::System.Runtime.InteropServices.HandleRef jarg6); + [global::System.Runtime.InteropServices.DllImport("mod_managed", EntryPoint="CSharp_FreeSWITCHfNative_switch_play_and_get_digits___")] public static extern int switch_play_and_get_digits(global::System.Runtime.InteropServices.HandleRef jarg1, uint jarg2, uint jarg3, uint jarg4, uint jarg5, string jarg6, string jarg7, string jarg8, string jarg9, string jarg10, uint jarg11, string jarg12, uint jarg13, string jarg14); @@ -25818,6 +25978,9 @@ class freeswitchPINVOKE { [global::System.Runtime.InteropServices.DllImport("mod_managed", EntryPoint="CSharp_FreeSWITCHfNative_switch_ivr_record_session_mask___")] public static extern int switch_ivr_record_session_mask(global::System.Runtime.InteropServices.HandleRef jarg1, string jarg2, int jarg3); + [global::System.Runtime.InteropServices.DllImport("mod_managed", EntryPoint="CSharp_FreeSWITCHfNative_switch_ivr_record_session_pause___")] + public static extern int switch_ivr_record_session_pause(global::System.Runtime.InteropServices.HandleRef jarg1, string jarg2, int jarg3); + [global::System.Runtime.InteropServices.DllImport("mod_managed", EntryPoint="CSharp_FreeSWITCHfNative_switch_ivr_stop_video_write_overlay_session___")] public static extern int switch_ivr_stop_video_write_overlay_session(global::System.Runtime.InteropServices.HandleRef jarg1); @@ -25917,6 +26080,9 @@ class freeswitchPINVOKE { [global::System.Runtime.InteropServices.DllImport("mod_managed", EntryPoint="CSharp_FreeSWITCHfNative_switch_ivr_orig_and_bridge___")] public static extern int switch_ivr_orig_and_bridge(global::System.Runtime.InteropServices.HandleRef jarg1, string jarg2, global::System.Runtime.InteropServices.HandleRef jarg3, global::System.Runtime.InteropServices.HandleRef jarg4); + [global::System.Runtime.InteropServices.DllImport("mod_managed", EntryPoint="CSharp_FreeSWITCHfNative_switch_ivr_send_prompt___")] + public static extern int switch_ivr_send_prompt(global::System.Runtime.InteropServices.HandleRef jarg1, string jarg2, string jarg3, string jarg4); + [global::System.Runtime.InteropServices.DllImport("mod_managed", EntryPoint="CSharp_FreeSWITCHfNative_switch_ivr_play_and_collect_input___")] public static extern int switch_ivr_play_and_collect_input(global::System.Runtime.InteropServices.HandleRef jarg1, string jarg2, string jarg3, string jarg4, int jarg5, int jarg6, string jarg7, uint jarg8, global::System.Runtime.InteropServices.HandleRef jarg9, ref string jarg10, string jarg11, global::System.Runtime.InteropServices.HandleRef jarg12); @@ -26481,6 +26647,18 @@ class freeswitchPINVOKE { [global::System.Runtime.InteropServices.DllImport("mod_managed", EntryPoint="CSharp_FreeSWITCHfNative_switch_log_node_t_tags_get___")] public static extern global::System.IntPtr switch_log_node_t_tags_get(global::System.Runtime.InteropServices.HandleRef jarg1); + [global::System.Runtime.InteropServices.DllImport("mod_managed", EntryPoint="CSharp_FreeSWITCHfNative_switch_log_node_t_sequence_set___")] + public static extern void switch_log_node_t_sequence_set(global::System.Runtime.InteropServices.HandleRef jarg1, long jarg2); + + [global::System.Runtime.InteropServices.DllImport("mod_managed", EntryPoint="CSharp_FreeSWITCHfNative_switch_log_node_t_sequence_get___")] + public static extern long switch_log_node_t_sequence_get(global::System.Runtime.InteropServices.HandleRef jarg1); + + [global::System.Runtime.InteropServices.DllImport("mod_managed", EntryPoint="CSharp_FreeSWITCHfNative_switch_log_node_t_meta_set___")] + public static extern void switch_log_node_t_meta_set(global::System.Runtime.InteropServices.HandleRef jarg1, global::System.Runtime.InteropServices.HandleRef jarg2); + + [global::System.Runtime.InteropServices.DllImport("mod_managed", EntryPoint="CSharp_FreeSWITCHfNative_switch_log_node_t_meta_get___")] + public static extern global::System.IntPtr switch_log_node_t_meta_get(global::System.Runtime.InteropServices.HandleRef jarg1); + [global::System.Runtime.InteropServices.DllImport("mod_managed", EntryPoint="CSharp_FreeSWITCHfNative_new_switch_log_node_t___")] public static extern global::System.IntPtr new_switch_log_node_t(); @@ -26589,6 +26767,12 @@ class freeswitchPINVOKE { [global::System.Runtime.InteropServices.DllImport("mod_managed", EntryPoint="CSharp_FreeSWITCHfNative_switch_log_json_format_t_timestamp_divisor_get___")] public static extern double switch_log_json_format_t_timestamp_divisor_get(global::System.Runtime.InteropServices.HandleRef jarg1); + [global::System.Runtime.InteropServices.DllImport("mod_managed", EntryPoint="CSharp_FreeSWITCHfNative_switch_log_json_format_t_sequence_set___")] + public static extern void switch_log_json_format_t_sequence_set(global::System.Runtime.InteropServices.HandleRef jarg1, global::System.Runtime.InteropServices.HandleRef jarg2); + + [global::System.Runtime.InteropServices.DllImport("mod_managed", EntryPoint="CSharp_FreeSWITCHfNative_switch_log_json_format_t_sequence_get___")] + public static extern global::System.IntPtr switch_log_json_format_t_sequence_get(global::System.Runtime.InteropServices.HandleRef jarg1); + [global::System.Runtime.InteropServices.DllImport("mod_managed", EntryPoint="CSharp_FreeSWITCHfNative_new_switch_log_json_format_t___")] public static extern global::System.IntPtr new_switch_log_json_format_t(); @@ -26706,6 +26890,18 @@ class freeswitchPINVOKE { [global::System.Runtime.InteropServices.DllImport("mod_managed", EntryPoint="CSharp_FreeSWITCHfNative_switch_xml_refs_get___")] public static extern uint switch_xml_refs_get(global::System.Runtime.InteropServices.HandleRef jarg1); + [global::System.Runtime.InteropServices.DllImport("mod_managed", EntryPoint="CSharp_FreeSWITCHfNative_switch_xml_open_set___")] + public static extern void switch_xml_open_set(global::System.Runtime.InteropServices.HandleRef jarg1, string jarg2); + + [global::System.Runtime.InteropServices.DllImport("mod_managed", EntryPoint="CSharp_FreeSWITCHfNative_switch_xml_open_get___")] + public static extern string switch_xml_open_get(global::System.Runtime.InteropServices.HandleRef jarg1); + + [global::System.Runtime.InteropServices.DllImport("mod_managed", EntryPoint="CSharp_FreeSWITCHfNative_switch_xml_close_set___")] + public static extern void switch_xml_close_set(global::System.Runtime.InteropServices.HandleRef jarg1, string jarg2); + + [global::System.Runtime.InteropServices.DllImport("mod_managed", EntryPoint="CSharp_FreeSWITCHfNative_switch_xml_close_get___")] + public static extern string switch_xml_close_get(global::System.Runtime.InteropServices.HandleRef jarg1); + [global::System.Runtime.InteropServices.DllImport("mod_managed", EntryPoint="CSharp_FreeSWITCHfNative_new_switch_xml___")] public static extern global::System.IntPtr new_switch_xml(); @@ -31671,6 +31867,7 @@ public enum switch_channel_cap_t { CC_IO_OVERRIDE, CC_RTP_RTT, CC_MSRP, + CC_MUTE_VIA_MEDIA_STREAM, CC_FLAG_MAX } @@ -31762,6 +31959,7 @@ public enum switch_channel_flag_t { CF_INTERCEPTED, CF_VIDEO_REFRESH_REQ, CF_MANUAL_VID_REFRESH, + CF_MANUAL_MEDIA_PARAMS, CF_SERVICE_AUDIO, CF_SERVICE_VIDEO, CF_ZRTP_PASSTHRU_REQ, @@ -31795,6 +31993,7 @@ public enum switch_channel_flag_t { CF_T38_PASSTHRU, CF_DROP_DTMF, CF_REINVITE, + CF_NOSDP_REINVITE, CF_AUTOFLUSH_DURING_BRIDGE, CF_RTP_NOTIMER_DURING_BRIDGE, CF_AVPF, @@ -31822,7 +32021,7 @@ public enum switch_channel_flag_t { CF_VIDEO_DECODED_READ, CF_VIDEO_DEBUG_READ, CF_VIDEO_DEBUG_WRITE, - CF_VIDEO_ONLY, + CF_NO_RECOVER, CF_VIDEO_READY, CF_VIDEO_MIRROR_INPUT, CF_VIDEO_READ_FILE_ATTACHED, @@ -31856,6 +32055,10 @@ public enum switch_channel_flag_t { CF_STATE_REPEAT, CF_WANT_DTLSv1_2, CF_RFC7329_COMPAT, + CF_REATTACHED, + CF_VIDEO_READ_TAPPED, + CF_VIDEO_WRITE_TAPPED, + CF_DEVICES_CHANGED, CF_FLAG_MAX } @@ -33932,6 +34135,7 @@ public enum switch_core_session_message_types_t { SWITCH_MESSAGE_INDICATE_DEFLECT, SWITCH_MESSAGE_INDICATE_VIDEO_REFRESH_REQ, SWITCH_MESSAGE_INDICATE_DISPLAY, + SWITCH_MESSAGE_INDICATE_MEDIA_PARAMS, SWITCH_MESSAGE_INDICATE_TRANSCODING_NECESSARY, SWITCH_MESSAGE_INDICATE_AUDIO_SYNC, SWITCH_MESSAGE_INDICATE_VIDEO_SYNC, @@ -33968,6 +34172,7 @@ public enum switch_core_session_message_types_t { SWITCH_MESSAGE_RESAMPLE_EVENT, SWITCH_MESSAGE_HEARTBEAT_EVENT, SWITCH_MESSAGE_INDICATE_SESSION_ID, + SWITCH_MESSAGE_INDICATE_PROMPT, SWITCH_MESSAGE_INVALID } @@ -36971,6 +37176,7 @@ public enum switch_event_types_t { SWITCH_EVENT_SEND_INFO, SWITCH_EVENT_RECV_INFO, SWITCH_EVENT_RECV_RTCP_MESSAGE, + SWITCH_EVENT_SEND_RTCP_MESSAGE, SWITCH_EVENT_CALL_SECURE, SWITCH_EVENT_NAT, SWITCH_EVENT_RECORD_START, @@ -41563,6 +41769,17 @@ public class switch_log_json_format_t : global::System.IDisposable { } } + public switch_log_json_format_item_t sequence { + set { + freeswitchPINVOKE.switch_log_json_format_t_sequence_set(swigCPtr, switch_log_json_format_item_t.getCPtr(value)); + } + get { + global::System.IntPtr cPtr = freeswitchPINVOKE.switch_log_json_format_t_sequence_get(swigCPtr); + switch_log_json_format_item_t ret = (cPtr == global::System.IntPtr.Zero) ? null : new switch_log_json_format_item_t(cPtr, false); + return ret; + } + } + public switch_log_json_format_t() : this(freeswitchPINVOKE.new_switch_log_json_format_t(), true) { } @@ -41761,6 +41978,27 @@ public class switch_log_node_t : global::System.IDisposable { } } + public long sequence { + set { + freeswitchPINVOKE.switch_log_node_t_sequence_set(swigCPtr, value); + } + get { + long ret = freeswitchPINVOKE.switch_log_node_t_sequence_get(swigCPtr); + return ret; + } + } + + public SWIGTYPE_p_cJSON meta { + set { + freeswitchPINVOKE.switch_log_node_t_meta_set(swigCPtr, SWIGTYPE_p_cJSON.getCPtr(value)); + } + get { + global::System.IntPtr cPtr = freeswitchPINVOKE.switch_log_node_t_meta_get(swigCPtr); + SWIGTYPE_p_cJSON ret = (cPtr == global::System.IntPtr.Zero) ? null : new SWIGTYPE_p_cJSON(cPtr, false); + return ret; + } + } + public switch_log_node_t() : this(freeswitchPINVOKE.new_switch_log_node_t(), true) { } @@ -41949,7 +42187,8 @@ namespace FreeSWITCH.Native { SMBF_SPY_VIDEO_STREAM_BLEG = (1 << 23), SMBF_READ_VIDEO_PATCH = (1 << 24), SMBF_READ_TEXT_STREAM = (1 << 25), - SMBF_FIRST = (1 << 26) + SMBF_FIRST = (1 << 26), + SMBF_PAUSE = (1 << 27) } } @@ -42163,6 +42402,16 @@ public class switch_mm_t : global::System.IDisposable { } } + public int source_kps { + set { + freeswitchPINVOKE.switch_mm_t_source_kps_set(swigCPtr, value); + } + get { + int ret = freeswitchPINVOKE.switch_mm_t_source_kps_get(swigCPtr); + return ret; + } + } + public int vbuf { set { freeswitchPINVOKE.switch_mm_t_vbuf_set(swigCPtr, value); @@ -43413,6 +43662,9 @@ public enum switch_rtp_flag_t { SWITCH_RTP_FLAG_PASSTHRU, SWITCH_RTP_FLAG_SECURE_SEND_MKI, SWITCH_RTP_FLAG_SECURE_RECV_MKI, + SWITCH_RTP_FLAG_SRTP_HANGUP_ON_ERROR, + SWITCH_RTP_FLAG_AUDIO_FIRE_SEND_RTCP_EVENT, + SWITCH_RTP_FLAG_VIDEO_FIRE_SEND_RTCP_EVENT, SWITCH_RTP_FLAG_INVALID } @@ -45075,7 +45327,9 @@ public enum switch_session_ctl_t { SCSC_SPS_PEAK, SCSC_SPS_PEAK_FIVEMIN, SCSC_SESSIONS_PEAK, - SCSC_SESSIONS_PEAK_FIVEMIN + SCSC_SESSIONS_PEAK_FIVEMIN, + SCSC_MDNS_RESOLVE, + SCSC_SHUTDOWN_CAUSE } } @@ -46523,6 +46777,16 @@ public class switch_thread_data_t : global::System.IDisposable { } } + public int running { + set { + freeswitchPINVOKE.switch_thread_data_t_running_set(swigCPtr, value); + } + get { + int ret = freeswitchPINVOKE.switch_thread_data_t_running_get(swigCPtr); + return ret; + } + } + public SWIGTYPE_p_apr_pool_t pool { set { freeswitchPINVOKE.switch_thread_data_t_pool_set(swigCPtr, SWIGTYPE_p_apr_pool_t.getCPtr(value)); @@ -47788,6 +48052,26 @@ public class switch_xml : global::System.IDisposable { } } + public string open { + set { + freeswitchPINVOKE.switch_xml_open_set(swigCPtr, value); + } + get { + string ret = freeswitchPINVOKE.switch_xml_open_get(swigCPtr); + return ret; + } + } + + public string close { + set { + freeswitchPINVOKE.switch_xml_close_set(swigCPtr, value); + } + get { + string ret = freeswitchPINVOKE.switch_xml_close_get(swigCPtr); + return ret; + } + } + public switch_xml() : this(freeswitchPINVOKE.new_switch_xml(), true) { } diff --git a/src/mod/languages/mod_python/README.md b/src/mod/languages/mod_python/README.md new file mode 100644 index 0000000000..ad0281863c --- /dev/null +++ b/src/mod/languages/mod_python/README.md @@ -0,0 +1,6 @@ +## WARNING: new default module is mod_python3 + +`freeswitch-mod-python` debian package is NOT going to be installed by default. +`freeswitch-mod-python3` will be installed instead. + +You should remove `freeswitch-mod-python3` package and install `freeswitch-mod-python` manually if you want. diff --git a/src/mod/languages/mod_python/hack.diff b/src/mod/languages/mod_python/hack.diff index 27bbe275e2..5732630bba 100644 --- a/src/mod/languages/mod_python/hack.diff +++ b/src/mod/languages/mod_python/hack.diff @@ -1,5 +1,33 @@ --- mod_python_wrap.cpp.old 2015-06-16 12:56:23.868000000 -0500 +++ mod_python_wrap.cpp 2015-06-16 12:56:32.268000000 -0500 +@@ -3500,7 +3500,9 @@ SWIG_AsCharArray(PyObject * obj, char *val, size_t size) + if (csize <= size) { + if (val) { + if (csize) memcpy(val, cptr, csize*sizeof(char)); ++#ifndef __clang_analyzer__ + if (csize < size) memset(val + csize, 0, (size - csize)*sizeof(char)); ++#endif + } + if (alloc == SWIG_NEWOBJ) { + delete[] cptr; +@@ -4677,7 +4677,7 @@ SWIGINTERN PyObject *_wrap_DTMF_digit_set(PyObject *SWIGUNUSEDPARM(self), PyObje + char arg2 ; + void *argp1 = 0 ; + int res1 = 0 ; +- char val2 ; ++ char val2 = '\0'; + int ecode2 = 0 ; + PyObject * obj0 = 0 ; + PyObject * obj1 = 0 ; +@@ -4787,7 +4787,7 @@ SWIGINTERN PyObject *_wrap_new_DTMF(PyObject *SWIGUNUSEDPARM(self), PyObject *ar + PyObject *resultobj = 0; + char arg1 ; + uint32_t arg2 = (uint32_t) SWITCH_DEFAULT_DTMF_DURATION ; +- char val1 ; ++ char val1 = '\0'; + int ecode1 = 0 ; + void *argp2 ; + int res2 = 0 ; @@ -6198,7 +6198,9 @@ } arg3 = static_cast< int >(val3); @@ -79,3 +107,11 @@ return resultobj; fail: return NULL; +@@ -10492,6 +10492,7 @@ SWIGINTERN PyObject *_wrap_Session_setSelf(PyObject *SWIGUNUSEDPARM(self), PyObj + SWIG_exception_fail(SWIG_ArgError(res1), "in method '" "Session_setSelf" "', argument " "1"" of type '" "PYTHON::Session *""'"); + } + arg1 = reinterpret_cast< PYTHON::Session * >(argp1); ++ if (!arg1) SWIG_exception_fail(SWIG_ValueError, "in method '" "Session_setSelf" "', argument " "1"" is NULL"); + arg2 = obj1; + (arg1)->setSelf(arg2); + resultobj = SWIG_Py_Void(); diff --git a/src/mod/languages/mod_python/mod_python_wrap.cpp b/src/mod/languages/mod_python/mod_python_wrap.cpp index 227b441b59..bd4985bbbe 100644 --- a/src/mod/languages/mod_python/mod_python_wrap.cpp +++ b/src/mod/languages/mod_python/mod_python_wrap.cpp @@ -3500,7 +3500,9 @@ SWIG_AsCharArray(PyObject * obj, char *val, size_t size) if (csize <= size) { if (val) { if (csize) memcpy(val, cptr, csize*sizeof(char)); +#ifndef __clang_analyzer__ if (csize < size) memset(val + csize, 0, (size - csize)*sizeof(char)); +#endif } if (alloc == SWIG_NEWOBJ) { delete[] cptr; @@ -4677,7 +4679,7 @@ SWIGINTERN PyObject *_wrap_DTMF_digit_set(PyObject *SWIGUNUSEDPARM(self), PyObje char arg2 ; void *argp1 = 0 ; int res1 = 0 ; - char val2 ; + char val2 = '\0'; int ecode2 = 0 ; PyObject * obj0 = 0 ; PyObject * obj1 = 0 ; @@ -4787,7 +4789,7 @@ SWIGINTERN PyObject *_wrap_new_DTMF(PyObject *SWIGUNUSEDPARM(self), PyObject *ar PyObject *resultobj = 0; char arg1 ; uint32_t arg2 = (uint32_t) SWITCH_DEFAULT_DTMF_DURATION ; - char val1 ; + char val1 = '\0'; int ecode1 = 0 ; void *argp2 ; int res2 = 0 ; @@ -10492,6 +10494,7 @@ SWIGINTERN PyObject *_wrap_Session_setSelf(PyObject *SWIGUNUSEDPARM(self), PyObj SWIG_exception_fail(SWIG_ArgError(res1), "in method '" "Session_setSelf" "', argument " "1"" of type '" "PYTHON::Session *""'"); } arg1 = reinterpret_cast< PYTHON::Session * >(argp1); + if (!arg1) SWIG_exception_fail(SWIG_ValueError, "in method '" "Session_setSelf" "', argument " "1"" is NULL"); arg2 = obj1; (arg1)->setSelf(arg2); resultobj = SWIG_Py_Void(); diff --git a/src/mod/languages/mod_python3/.gitattributes b/src/mod/languages/mod_python3/.gitattributes new file mode 100644 index 0000000000..98d05d51d6 --- /dev/null +++ b/src/mod/languages/mod_python3/.gitattributes @@ -0,0 +1,2 @@ +mod_python_wrap.cpp -diff +freeswitch.py -diff diff --git a/src/mod/languages/mod_python3/Makefile.am b/src/mod/languages/mod_python3/Makefile.am new file mode 100644 index 0000000000..796f672234 --- /dev/null +++ b/src/mod/languages/mod_python3/Makefile.am @@ -0,0 +1,30 @@ +include $(top_srcdir)/build/modmake.rulesam +MODNAME=mod_python3 + +PYMOD=freeswitch +PYTHON3_SITE_DIR=@PYTHON3_SITE_DIR@ + +SWIGCFILE=../../../switch_swig.c +SWIGIFILE=../../../switch_swig.i + +mod_LTLIBRARIES = mod_python3.la +mod_python3_la_SOURCES = mod_python3.c freeswitch_python.cpp mod_python_wrap.cpp +mod_python3_la_CFLAGS = $(SWITCH_AM_CFLAGS) +mod_python3_la_CPPFLAGS = @PYTHON3_CFLAGS@ -I$(switch_srcdir)/libs/libteletone/src/ $(SWITCH_AM_CPPFLAGS) +mod_python3_la_LIBADD = $(switch_builddir)/libfreeswitch.la +mod_python3_la_LDFLAGS = -avoid-version -module -no-undefined -shared @PYTHON3_LDFLAGS@ + +reswig: swigclean mod_python_wrap.cpp + +swigclean: clean + rm -f mod_python_wrap.* freeswitch.py + +mod_python_wrap.cpp: mod_python_extra.c hack.diff + swig3.0 -python -c++ -I../../../../src/include -oh mod_python_wrap.h -o mod_python_wrap.cpp mod_python.i + echo "#include \"mod_python_extra.c\"" >> mod_python_wrap.cpp + patch -s -p0 -i hack.diff + +install-data-local: + mkdir -m755 -p $(DESTDIR)$(PYTHON3_SITE_DIR) + cp -f freeswitch.py $(DESTDIR)$(PYTHON3_SITE_DIR) + diff --git a/src/mod/languages/mod_python3/README.md b/src/mod/languages/mod_python3/README.md new file mode 100644 index 0000000000..ad0281863c --- /dev/null +++ b/src/mod/languages/mod_python3/README.md @@ -0,0 +1,6 @@ +## WARNING: new default module is mod_python3 + +`freeswitch-mod-python` debian package is NOT going to be installed by default. +`freeswitch-mod-python3` will be installed instead. + +You should remove `freeswitch-mod-python3` package and install `freeswitch-mod-python` manually if you want. diff --git a/src/mod/languages/mod_python3/freeswitch.py b/src/mod/languages/mod_python3/freeswitch.py new file mode 100644 index 0000000000..48ccf472f1 --- /dev/null +++ b/src/mod/languages/mod_python3/freeswitch.py @@ -0,0 +1,702 @@ +# This file was automatically generated by SWIG (http://www.swig.org). +# Version 3.0.12 +# +# Do not make changes to this file unless you know what you are doing--modify +# the SWIG interface file instead. + +from sys import version_info as _swig_python_version_info +if _swig_python_version_info >= (2, 7, 0): + def swig_import_helper(): + import importlib + pkg = __name__.rpartition('.')[0] + mname = '.'.join((pkg, '_freeswitch')).lstrip('.') + try: + return importlib.import_module(mname) + except ImportError: + return importlib.import_module('_freeswitch') + _freeswitch = swig_import_helper() + del swig_import_helper +elif _swig_python_version_info >= (2, 6, 0): + def swig_import_helper(): + from os.path import dirname + import imp + fp = None + try: + fp, pathname, description = imp.find_module('_freeswitch', [dirname(__file__)]) + except ImportError: + import _freeswitch + return _freeswitch + try: + _mod = imp.load_module('_freeswitch', fp, pathname, description) + finally: + if fp is not None: + fp.close() + return _mod + _freeswitch = swig_import_helper() + del swig_import_helper +else: + import _freeswitch +del _swig_python_version_info + +try: + _swig_property = property +except NameError: + pass # Python < 2.2 doesn't have 'property'. + +try: + import builtins as __builtin__ +except ImportError: + import __builtin__ + +def _swig_setattr_nondynamic(self, class_type, name, value, static=1): + if (name == "thisown"): + return self.this.own(value) + if (name == "this"): + if type(value).__name__ == 'SwigPyObject': + self.__dict__[name] = value + return + method = class_type.__swig_setmethods__.get(name, None) + if method: + return method(self, value) + if (not static): + if _newclass: + object.__setattr__(self, name, value) + else: + self.__dict__[name] = value + else: + raise AttributeError("You cannot add attributes to %s" % self) + + +def _swig_setattr(self, class_type, name, value): + return _swig_setattr_nondynamic(self, class_type, name, value, 0) + + +def _swig_getattr(self, class_type, name): + if (name == "thisown"): + return self.this.own() + method = class_type.__swig_getmethods__.get(name, None) + if method: + return method(self) + raise AttributeError("'%s' object has no attribute '%s'" % (class_type.__name__, name)) + + +def _swig_repr(self): + try: + strthis = "proxy of " + self.this.__repr__() + except __builtin__.Exception: + strthis = "" + return "<%s.%s; %s >" % (self.__class__.__module__, self.__class__.__name__, strthis,) + +try: + _object = object + _newclass = 1 +except __builtin__.Exception: + class _object: + pass + _newclass = 0 + + +def setGlobalVariable(var_name, var_val): + return _freeswitch.setGlobalVariable(var_name, var_val) +setGlobalVariable = _freeswitch.setGlobalVariable + +def getGlobalVariable(var_name): + return _freeswitch.getGlobalVariable(var_name) +getGlobalVariable = _freeswitch.getGlobalVariable + +def consoleLog(level_str, msg): + return _freeswitch.consoleLog(level_str, msg) +consoleLog = _freeswitch.consoleLog + +def consoleLog2(level_str, file, func, line, msg): + return _freeswitch.consoleLog2(level_str, file, func, line, msg) +consoleLog2 = _freeswitch.consoleLog2 + +def consoleCleanLog(msg): + return _freeswitch.consoleCleanLog(msg) +consoleCleanLog = _freeswitch.consoleCleanLog + +def running(): + return _freeswitch.running() +running = _freeswitch.running + +def email(to, arg2, headers=None, body=None, file=None, convert_cmd=None, convert_ext=None): + return _freeswitch.email(to, arg2, headers, body, file, convert_cmd, convert_ext) +email = _freeswitch.email +class IVRMenu(_object): + __swig_setmethods__ = {} + __setattr__ = lambda self, name, value: _swig_setattr(self, IVRMenu, name, value) + __swig_getmethods__ = {} + __getattr__ = lambda self, name: _swig_getattr(self, IVRMenu, name) + __repr__ = _swig_repr + + def __init__(self, main, name, greeting_sound, short_greeting_sound, invalid_sound, exit_sound, transfer_sound, confirm_macro, confirm_key, tts_engine, tts_voice, confirm_attempts, inter_timeout, digit_len, timeout, max_failures, max_timeouts): + this = _freeswitch.new_IVRMenu(main, name, greeting_sound, short_greeting_sound, invalid_sound, exit_sound, transfer_sound, confirm_macro, confirm_key, tts_engine, tts_voice, confirm_attempts, inter_timeout, digit_len, timeout, max_failures, max_timeouts) + try: + self.this.append(this) + except __builtin__.Exception: + self.this = this + __swig_destroy__ = _freeswitch.delete_IVRMenu + __del__ = lambda self: None + + def bindAction(self, action, arg, bind): + return _freeswitch.IVRMenu_bindAction(self, action, arg, bind) + + def execute(self, session, name): + return _freeswitch.IVRMenu_execute(self, session, name) +IVRMenu_swigregister = _freeswitch.IVRMenu_swigregister +IVRMenu_swigregister(IVRMenu) + +class API(_object): + __swig_setmethods__ = {} + __setattr__ = lambda self, name, value: _swig_setattr(self, API, name, value) + __swig_getmethods__ = {} + __getattr__ = lambda self, name: _swig_getattr(self, API, name) + __repr__ = _swig_repr + + def __init__(self, s=None): + this = _freeswitch.new_API(s) + try: + self.this.append(this) + except __builtin__.Exception: + self.this = this + __swig_destroy__ = _freeswitch.delete_API + __del__ = lambda self: None + + def execute(self, command, data=None): + return _freeswitch.API_execute(self, command, data) + + def executeString(self, command): + return _freeswitch.API_executeString(self, command) + + def getTime(self): + return _freeswitch.API_getTime(self) +API_swigregister = _freeswitch.API_swigregister +API_swigregister(API) + +class input_callback_state_t(_object): + __swig_setmethods__ = {} + __setattr__ = lambda self, name, value: _swig_setattr(self, input_callback_state_t, name, value) + __swig_getmethods__ = {} + __getattr__ = lambda self, name: _swig_getattr(self, input_callback_state_t, name) + __repr__ = _swig_repr + __swig_setmethods__["function"] = _freeswitch.input_callback_state_t_function_set + __swig_getmethods__["function"] = _freeswitch.input_callback_state_t_function_get + if _newclass: + function = _swig_property(_freeswitch.input_callback_state_t_function_get, _freeswitch.input_callback_state_t_function_set) + __swig_setmethods__["threadState"] = _freeswitch.input_callback_state_t_threadState_set + __swig_getmethods__["threadState"] = _freeswitch.input_callback_state_t_threadState_get + if _newclass: + threadState = _swig_property(_freeswitch.input_callback_state_t_threadState_get, _freeswitch.input_callback_state_t_threadState_set) + __swig_setmethods__["extra"] = _freeswitch.input_callback_state_t_extra_set + __swig_getmethods__["extra"] = _freeswitch.input_callback_state_t_extra_get + if _newclass: + extra = _swig_property(_freeswitch.input_callback_state_t_extra_get, _freeswitch.input_callback_state_t_extra_set) + __swig_setmethods__["funcargs"] = _freeswitch.input_callback_state_t_funcargs_set + __swig_getmethods__["funcargs"] = _freeswitch.input_callback_state_t_funcargs_get + if _newclass: + funcargs = _swig_property(_freeswitch.input_callback_state_t_funcargs_get, _freeswitch.input_callback_state_t_funcargs_set) + + def __init__(self): + this = _freeswitch.new_input_callback_state_t() + try: + self.this.append(this) + except __builtin__.Exception: + self.this = this + __swig_destroy__ = _freeswitch.delete_input_callback_state_t + __del__ = lambda self: None +input_callback_state_t_swigregister = _freeswitch.input_callback_state_t_swigregister +input_callback_state_t_swigregister(input_callback_state_t) + +S_HUP = _freeswitch.S_HUP +S_FREE = _freeswitch.S_FREE +S_RDLOCK = _freeswitch.S_RDLOCK +class DTMF(_object): + __swig_setmethods__ = {} + __setattr__ = lambda self, name, value: _swig_setattr(self, DTMF, name, value) + __swig_getmethods__ = {} + __getattr__ = lambda self, name: _swig_getattr(self, DTMF, name) + __repr__ = _swig_repr + __swig_setmethods__["digit"] = _freeswitch.DTMF_digit_set + __swig_getmethods__["digit"] = _freeswitch.DTMF_digit_get + if _newclass: + digit = _swig_property(_freeswitch.DTMF_digit_get, _freeswitch.DTMF_digit_set) + __swig_setmethods__["duration"] = _freeswitch.DTMF_duration_set + __swig_getmethods__["duration"] = _freeswitch.DTMF_duration_get + if _newclass: + duration = _swig_property(_freeswitch.DTMF_duration_get, _freeswitch.DTMF_duration_set) + + def __init__(self, *args): + this = _freeswitch.new_DTMF(*args) + try: + self.this.append(this) + except __builtin__.Exception: + self.this = this + __swig_destroy__ = _freeswitch.delete_DTMF + __del__ = lambda self: None +DTMF_swigregister = _freeswitch.DTMF_swigregister +DTMF_swigregister(DTMF) + +class Stream(_object): + __swig_setmethods__ = {} + __setattr__ = lambda self, name, value: _swig_setattr(self, Stream, name, value) + __swig_getmethods__ = {} + __getattr__ = lambda self, name: _swig_getattr(self, Stream, name) + __repr__ = _swig_repr + + def __init__(self, *args): + this = _freeswitch.new_Stream(*args) + try: + self.this.append(this) + except __builtin__.Exception: + self.this = this + __swig_destroy__ = _freeswitch.delete_Stream + __del__ = lambda self: None + + def read(self, len): + return _freeswitch.Stream_read(self, len) + + def write(self, data): + return _freeswitch.Stream_write(self, data) + + def raw_write(self, data, len): + return _freeswitch.Stream_raw_write(self, data, len) + + def get_data(self): + return _freeswitch.Stream_get_data(self) +Stream_swigregister = _freeswitch.Stream_swigregister +Stream_swigregister(Stream) + +class Event(_object): + __swig_setmethods__ = {} + __setattr__ = lambda self, name, value: _swig_setattr(self, Event, name, value) + __swig_getmethods__ = {} + __getattr__ = lambda self, name: _swig_getattr(self, Event, name) + __repr__ = _swig_repr + __swig_setmethods__["event"] = _freeswitch.Event_event_set + __swig_getmethods__["event"] = _freeswitch.Event_event_get + if _newclass: + event = _swig_property(_freeswitch.Event_event_get, _freeswitch.Event_event_set) + __swig_setmethods__["serialized_string"] = _freeswitch.Event_serialized_string_set + __swig_getmethods__["serialized_string"] = _freeswitch.Event_serialized_string_get + if _newclass: + serialized_string = _swig_property(_freeswitch.Event_serialized_string_get, _freeswitch.Event_serialized_string_set) + __swig_setmethods__["mine"] = _freeswitch.Event_mine_set + __swig_getmethods__["mine"] = _freeswitch.Event_mine_get + if _newclass: + mine = _swig_property(_freeswitch.Event_mine_get, _freeswitch.Event_mine_set) + + def __init__(self, *args): + this = _freeswitch.new_Event(*args) + try: + self.this.append(this) + except __builtin__.Exception: + self.this = this + __swig_destroy__ = _freeswitch.delete_Event + __del__ = lambda self: None + + def chat_execute(self, app, data=None): + return _freeswitch.Event_chat_execute(self, app, data) + + def chat_send(self, dest_proto=None): + return _freeswitch.Event_chat_send(self, dest_proto) + + def serialize(self, format=None): + return _freeswitch.Event_serialize(self, format) + + def setPriority(self, *args): + return _freeswitch.Event_setPriority(self, *args) + + def getHeader(self, header_name): + return _freeswitch.Event_getHeader(self, header_name) + + def getBody(self): + return _freeswitch.Event_getBody(self) + + def getType(self): + return _freeswitch.Event_getType(self) + + def addBody(self, value): + return _freeswitch.Event_addBody(self, value) + + def addHeader(self, header_name, value): + return _freeswitch.Event_addHeader(self, header_name, value) + + def delHeader(self, header_name): + return _freeswitch.Event_delHeader(self, header_name) + + def fire(self): + return _freeswitch.Event_fire(self) + + def merge(self, to_merge): + return _freeswitch.Event_merge(self, to_merge) +Event_swigregister = _freeswitch.Event_swigregister +Event_swigregister(Event) + +class EventConsumer(_object): + __swig_setmethods__ = {} + __setattr__ = lambda self, name, value: _swig_setattr(self, EventConsumer, name, value) + __swig_getmethods__ = {} + __getattr__ = lambda self, name: _swig_getattr(self, EventConsumer, name) + __repr__ = _swig_repr + __swig_setmethods__["events"] = _freeswitch.EventConsumer_events_set + __swig_getmethods__["events"] = _freeswitch.EventConsumer_events_get + if _newclass: + events = _swig_property(_freeswitch.EventConsumer_events_get, _freeswitch.EventConsumer_events_set) + __swig_setmethods__["e_event_id"] = _freeswitch.EventConsumer_e_event_id_set + __swig_getmethods__["e_event_id"] = _freeswitch.EventConsumer_e_event_id_get + if _newclass: + e_event_id = _swig_property(_freeswitch.EventConsumer_e_event_id_get, _freeswitch.EventConsumer_e_event_id_set) + __swig_setmethods__["e_callback"] = _freeswitch.EventConsumer_e_callback_set + __swig_getmethods__["e_callback"] = _freeswitch.EventConsumer_e_callback_get + if _newclass: + e_callback = _swig_property(_freeswitch.EventConsumer_e_callback_get, _freeswitch.EventConsumer_e_callback_set) + __swig_setmethods__["e_subclass_name"] = _freeswitch.EventConsumer_e_subclass_name_set + __swig_getmethods__["e_subclass_name"] = _freeswitch.EventConsumer_e_subclass_name_get + if _newclass: + e_subclass_name = _swig_property(_freeswitch.EventConsumer_e_subclass_name_get, _freeswitch.EventConsumer_e_subclass_name_set) + __swig_setmethods__["e_cb_arg"] = _freeswitch.EventConsumer_e_cb_arg_set + __swig_getmethods__["e_cb_arg"] = _freeswitch.EventConsumer_e_cb_arg_get + if _newclass: + e_cb_arg = _swig_property(_freeswitch.EventConsumer_e_cb_arg_get, _freeswitch.EventConsumer_e_cb_arg_set) + __swig_setmethods__["enodes"] = _freeswitch.EventConsumer_enodes_set + __swig_getmethods__["enodes"] = _freeswitch.EventConsumer_enodes_get + if _newclass: + enodes = _swig_property(_freeswitch.EventConsumer_enodes_get, _freeswitch.EventConsumer_enodes_set) + __swig_setmethods__["node_index"] = _freeswitch.EventConsumer_node_index_set + __swig_getmethods__["node_index"] = _freeswitch.EventConsumer_node_index_get + if _newclass: + node_index = _swig_property(_freeswitch.EventConsumer_node_index_get, _freeswitch.EventConsumer_node_index_set) + + def __init__(self, *args): + this = _freeswitch.new_EventConsumer(*args) + try: + self.this.append(this) + except __builtin__.Exception: + self.this = this + __swig_destroy__ = _freeswitch.delete_EventConsumer + __del__ = lambda self: None + + def bind(self, *args): + return _freeswitch.EventConsumer_bind(self, *args) + + def pop(self, block=0, timeout=0): + return _freeswitch.EventConsumer_pop(self, block, timeout) + + def cleanup(self): + return _freeswitch.EventConsumer_cleanup(self) +EventConsumer_swigregister = _freeswitch.EventConsumer_swigregister +EventConsumer_swigregister(EventConsumer) + +class CoreSession(_object): + __swig_setmethods__ = {} + __setattr__ = lambda self, name, value: _swig_setattr(self, CoreSession, name, value) + __swig_getmethods__ = {} + __getattr__ = lambda self, name: _swig_getattr(self, CoreSession, name) + + def __init__(self, *args, **kwargs): + raise AttributeError("No constructor defined - class is abstract") + __repr__ = _swig_repr + __swig_destroy__ = _freeswitch.delete_CoreSession + __del__ = lambda self: None + __swig_setmethods__["session"] = _freeswitch.CoreSession_session_set + __swig_getmethods__["session"] = _freeswitch.CoreSession_session_get + if _newclass: + session = _swig_property(_freeswitch.CoreSession_session_get, _freeswitch.CoreSession_session_set) + __swig_setmethods__["channel"] = _freeswitch.CoreSession_channel_set + __swig_getmethods__["channel"] = _freeswitch.CoreSession_channel_get + if _newclass: + channel = _swig_property(_freeswitch.CoreSession_channel_get, _freeswitch.CoreSession_channel_set) + __swig_setmethods__["flags"] = _freeswitch.CoreSession_flags_set + __swig_getmethods__["flags"] = _freeswitch.CoreSession_flags_get + if _newclass: + flags = _swig_property(_freeswitch.CoreSession_flags_get, _freeswitch.CoreSession_flags_set) + __swig_setmethods__["allocated"] = _freeswitch.CoreSession_allocated_set + __swig_getmethods__["allocated"] = _freeswitch.CoreSession_allocated_get + if _newclass: + allocated = _swig_property(_freeswitch.CoreSession_allocated_get, _freeswitch.CoreSession_allocated_set) + __swig_setmethods__["cb_state"] = _freeswitch.CoreSession_cb_state_set + __swig_getmethods__["cb_state"] = _freeswitch.CoreSession_cb_state_get + if _newclass: + cb_state = _swig_property(_freeswitch.CoreSession_cb_state_get, _freeswitch.CoreSession_cb_state_set) + __swig_setmethods__["hook_state"] = _freeswitch.CoreSession_hook_state_set + __swig_getmethods__["hook_state"] = _freeswitch.CoreSession_hook_state_get + if _newclass: + hook_state = _swig_property(_freeswitch.CoreSession_hook_state_get, _freeswitch.CoreSession_hook_state_set) + __swig_setmethods__["cause"] = _freeswitch.CoreSession_cause_set + __swig_getmethods__["cause"] = _freeswitch.CoreSession_cause_get + if _newclass: + cause = _swig_property(_freeswitch.CoreSession_cause_get, _freeswitch.CoreSession_cause_set) + __swig_setmethods__["uuid"] = _freeswitch.CoreSession_uuid_set + __swig_getmethods__["uuid"] = _freeswitch.CoreSession_uuid_get + if _newclass: + uuid = _swig_property(_freeswitch.CoreSession_uuid_get, _freeswitch.CoreSession_uuid_set) + __swig_setmethods__["tts_name"] = _freeswitch.CoreSession_tts_name_set + __swig_getmethods__["tts_name"] = _freeswitch.CoreSession_tts_name_get + if _newclass: + tts_name = _swig_property(_freeswitch.CoreSession_tts_name_get, _freeswitch.CoreSession_tts_name_set) + __swig_setmethods__["voice_name"] = _freeswitch.CoreSession_voice_name_set + __swig_getmethods__["voice_name"] = _freeswitch.CoreSession_voice_name_get + if _newclass: + voice_name = _swig_property(_freeswitch.CoreSession_voice_name_get, _freeswitch.CoreSession_voice_name_set) + + def insertFile(self, file, insert_file, sample_point): + return _freeswitch.CoreSession_insertFile(self, file, insert_file, sample_point) + + def answer(self): + return _freeswitch.CoreSession_answer(self) + + def _print(self, txt): + return _freeswitch.CoreSession__print(self, txt) + + def preAnswer(self): + return _freeswitch.CoreSession_preAnswer(self) + + def hangup(self, *args): + return _freeswitch.CoreSession_hangup(self, *args) + + def hangupState(self): + return _freeswitch.CoreSession_hangupState(self) + + def setVariable(self, var, val): + return _freeswitch.CoreSession_setVariable(self, var, val) + + def setPrivate(self, var, val): + return _freeswitch.CoreSession_setPrivate(self, var, val) + + def getPrivate(self, var): + return _freeswitch.CoreSession_getPrivate(self, var) + + def getVariable(self, var): + return _freeswitch.CoreSession_getVariable(self, var) + + def process_callback_result(self, result): + return _freeswitch.CoreSession_process_callback_result(self, result) + + def say(self, tosay, module_name, say_type, say_method, say_gender=None): + return _freeswitch.CoreSession_say(self, tosay, module_name, say_type, say_method, say_gender) + + def sayPhrase(self, *args): + return _freeswitch.CoreSession_sayPhrase(self, *args) + + def hangupCause(self): + return _freeswitch.CoreSession_hangupCause(self) + + def getState(self): + return _freeswitch.CoreSession_getState(self) + + def recordFile(self, file_name, time_limit=0, silence_threshold=0, silence_hits=0): + return _freeswitch.CoreSession_recordFile(self, file_name, time_limit, silence_threshold, silence_hits) + + def originate(self, a_leg_session, dest, timeout=60, handlers=None): + return _freeswitch.CoreSession_originate(self, a_leg_session, dest, timeout, handlers) + + def destroy(self): + return _freeswitch.CoreSession_destroy(self) + + def setDTMFCallback(self, cbfunc, funcargs): + return _freeswitch.CoreSession_setDTMFCallback(self, cbfunc, funcargs) + + def speak(self, text): + return _freeswitch.CoreSession_speak(self, text) + + def set_tts_parms(self, tts_name, voice_name): + return _freeswitch.CoreSession_set_tts_parms(self, tts_name, voice_name) + + def set_tts_params(self, tts_name, voice_name): + return _freeswitch.CoreSession_set_tts_params(self, tts_name, voice_name) + + def collectDigits(self, *args): + return _freeswitch.CoreSession_collectDigits(self, *args) + + def getDigits(self, *args): + return _freeswitch.CoreSession_getDigits(self, *args) + + def transfer(self, extension, dialplan=None, context=None): + return _freeswitch.CoreSession_transfer(self, extension, dialplan, context) + + def read(self, min_digits, max_digits, prompt_audio_file, timeout, valid_terminators, digit_timeout=0): + return _freeswitch.CoreSession_read(self, min_digits, max_digits, prompt_audio_file, timeout, valid_terminators, digit_timeout) + + def detectSpeech(self, arg0, arg1=None, arg2=None, arg3=None): + return _freeswitch.CoreSession_detectSpeech(self, arg0, arg1, arg2, arg3) + + def playAndGetDigits(self, min_digits, max_digits, max_tries, timeout, terminators, audio_files, bad_input_audio_files, digits_regex, var_name=None, digit_timeout=0, transfer_on_failure=None): + return _freeswitch.CoreSession_playAndGetDigits(self, min_digits, max_digits, max_tries, timeout, terminators, audio_files, bad_input_audio_files, digits_regex, var_name, digit_timeout, transfer_on_failure) + + def playAndDetectSpeech(self, file, engine, grammar): + return _freeswitch.CoreSession_playAndDetectSpeech(self, file, engine, grammar) + + def streamFile(self, file, starting_sample_count=0): + return _freeswitch.CoreSession_streamFile(self, file, starting_sample_count) + + def sleep(self, ms, sync=0): + return _freeswitch.CoreSession_sleep(self, ms, sync) + + def flushEvents(self): + return _freeswitch.CoreSession_flushEvents(self) + + def flushDigits(self): + return _freeswitch.CoreSession_flushDigits(self) + + def setAutoHangup(self, val): + return _freeswitch.CoreSession_setAutoHangup(self, val) + + def setHangupHook(self, hangup_func): + return _freeswitch.CoreSession_setHangupHook(self, hangup_func) + + def ready(self): + return _freeswitch.CoreSession_ready(self) + + def bridged(self): + return _freeswitch.CoreSession_bridged(self) + + def answered(self): + return _freeswitch.CoreSession_answered(self) + + def mediaReady(self): + return _freeswitch.CoreSession_mediaReady(self) + + def waitForAnswer(self, calling_session): + return _freeswitch.CoreSession_waitForAnswer(self, calling_session) + + def execute(self, app, data=None): + return _freeswitch.CoreSession_execute(self, app, data) + + def sendEvent(self, sendME): + return _freeswitch.CoreSession_sendEvent(self, sendME) + + def setEventData(self, e): + return _freeswitch.CoreSession_setEventData(self, e) + + def getXMLCDR(self): + return _freeswitch.CoreSession_getXMLCDR(self) + + def begin_allow_threads(self): + return _freeswitch.CoreSession_begin_allow_threads(self) + + def end_allow_threads(self): + return _freeswitch.CoreSession_end_allow_threads(self) + + def get_uuid(self): + return _freeswitch.CoreSession_get_uuid(self) + + def get_cb_args(self): + return _freeswitch.CoreSession_get_cb_args(self) + + def check_hangup_hook(self): + return _freeswitch.CoreSession_check_hangup_hook(self) + + def run_dtmf_callback(self, input, itype): + return _freeswitch.CoreSession_run_dtmf_callback(self, input, itype) + + def consoleLog(self, level_str, msg): + return _freeswitch.CoreSession_consoleLog(self, level_str, msg) + + def consoleLog2(self, level_str, file, func, line, msg): + return _freeswitch.CoreSession_consoleLog2(self, level_str, file, func, line, msg) +CoreSession_swigregister = _freeswitch.CoreSession_swigregister +CoreSession_swigregister(CoreSession) + + +def console_log(level_str, msg): + return _freeswitch.console_log(level_str, msg) +console_log = _freeswitch.console_log + +def console_log2(level_str, file, func, line, msg): + return _freeswitch.console_log2(level_str, file, func, line, msg) +console_log2 = _freeswitch.console_log2 + +def console_clean_log(msg): + return _freeswitch.console_clean_log(msg) +console_clean_log = _freeswitch.console_clean_log + +def msleep(ms): + return _freeswitch.msleep(ms) +msleep = _freeswitch.msleep + +def bridge(session_a, session_b): + return _freeswitch.bridge(session_a, session_b) +bridge = _freeswitch.bridge + +def hanguphook(session): + return _freeswitch.hanguphook(session) +hanguphook = _freeswitch.hanguphook + +def dtmf_callback(session, input, itype, buf, buflen): + return _freeswitch.dtmf_callback(session, input, itype, buf, buflen) +dtmf_callback = _freeswitch.dtmf_callback +class Session(CoreSession): + __swig_setmethods__ = {} + for _s in [CoreSession]: + __swig_setmethods__.update(getattr(_s, '__swig_setmethods__', {})) + __setattr__ = lambda self, name, value: _swig_setattr(self, Session, name, value) + __swig_getmethods__ = {} + for _s in [CoreSession]: + __swig_getmethods__.update(getattr(_s, '__swig_getmethods__', {})) + __getattr__ = lambda self, name: _swig_getattr(self, Session, name) + __repr__ = _swig_repr + + def __init__(self, *args): + this = _freeswitch.new_Session(*args) + try: + self.this.append(this) + except __builtin__.Exception: + self.this = this + __swig_destroy__ = _freeswitch.delete_Session + __del__ = lambda self: None + + def begin_allow_threads(self): + return _freeswitch.Session_begin_allow_threads(self) + + def end_allow_threads(self): + return _freeswitch.Session_end_allow_threads(self) + + def check_hangup_hook(self): + return _freeswitch.Session_check_hangup_hook(self) + + def destroy(self): + return _freeswitch.Session_destroy(self) + + def run_dtmf_callback(self, input, itype): + return _freeswitch.Session_run_dtmf_callback(self, input, itype) + + def setInputCallback(self, cbfunc, funcargs=None): + return _freeswitch.Session_setInputCallback(self, cbfunc, funcargs) + + def unsetInputCallback(self): + return _freeswitch.Session_unsetInputCallback(self) + + def setHangupHook(self, pyfunc, arg=None): + return _freeswitch.Session_setHangupHook(self, pyfunc, arg) + + def ready(self): + return _freeswitch.Session_ready(self) + __swig_setmethods__["cb_function"] = _freeswitch.Session_cb_function_set + __swig_getmethods__["cb_function"] = _freeswitch.Session_cb_function_get + if _newclass: + cb_function = _swig_property(_freeswitch.Session_cb_function_get, _freeswitch.Session_cb_function_set) + __swig_setmethods__["cb_arg"] = _freeswitch.Session_cb_arg_set + __swig_getmethods__["cb_arg"] = _freeswitch.Session_cb_arg_get + if _newclass: + cb_arg = _swig_property(_freeswitch.Session_cb_arg_get, _freeswitch.Session_cb_arg_set) + __swig_setmethods__["hangup_func"] = _freeswitch.Session_hangup_func_set + __swig_getmethods__["hangup_func"] = _freeswitch.Session_hangup_func_get + if _newclass: + hangup_func = _swig_property(_freeswitch.Session_hangup_func_get, _freeswitch.Session_hangup_func_set) + __swig_setmethods__["hangup_func_arg"] = _freeswitch.Session_hangup_func_arg_set + __swig_getmethods__["hangup_func_arg"] = _freeswitch.Session_hangup_func_arg_get + if _newclass: + hangup_func_arg = _swig_property(_freeswitch.Session_hangup_func_arg_get, _freeswitch.Session_hangup_func_arg_set) + + def setPython(self, state): + return _freeswitch.Session_setPython(self, state) + + def setSelf(self, state): + return _freeswitch.Session_setSelf(self, state) +Session_swigregister = _freeswitch.Session_swigregister +Session_swigregister(Session) + +# This file is compatible with both classic and new-style classes. + + diff --git a/src/mod/languages/mod_python3/freeswitch_python.cpp b/src/mod/languages/mod_python3/freeswitch_python.cpp new file mode 100644 index 0000000000..0893c47c91 --- /dev/null +++ b/src/mod/languages/mod_python3/freeswitch_python.cpp @@ -0,0 +1,342 @@ + +#include +#include "freeswitch_python.h" +using namespace PYTHON; + +#define py_init_vars() cb_function = cb_arg = hangup_func = hangup_func_arg = NULL; hh = mark = 0; TS = NULL + +#define PyString_AsString PyUnicode_AsUTF8 +#define PyString_Check PyUnicode_Check + +Session::Session():CoreSession() +{ + py_init_vars(); +} + +Session::Session(char *nuuid, CoreSession *a_leg):CoreSession(nuuid, a_leg) +{ + py_init_vars(); +} + +Session::Session(switch_core_session_t *new_session):CoreSession(new_session) +{ + py_init_vars(); +} +static switch_status_t python_hanguphook(switch_core_session_t *session_hungup); + +void Session::destroy(void) +{ + + if (!allocated) { + return; + } + + if (session) { + if (!channel) { + channel = switch_core_session_get_channel(session); + } + switch_channel_set_private(channel, "CoreSession", NULL); + switch_core_event_hook_remove_state_change(session, python_hanguphook); + } + + if (hangup_func) { + Py_DECREF(hangup_func); + hangup_func = NULL; + } + + if (hangup_func_arg) { + Py_DECREF(hangup_func_arg); + hangup_func_arg = NULL; + } + + if (cb_function) { + Py_DECREF(cb_function); + cb_function = NULL; + } + + if (cb_arg) { + Py_DECREF(cb_arg); + cb_arg = NULL; + } + + CoreSession::destroy(); +} + +Session::~Session() +{ + destroy(); +} + +bool Session::begin_allow_threads() +{ + + do_hangup_hook(); + + if (!TS) { + TS = PyEval_SaveThread(); + if (channel) { + switch_channel_set_private(channel, "SwapInThreadState", TS); + } + return true; + } + + return false; +} + +bool Session::end_allow_threads() +{ + + if (!TS) { + return false; + } + + PyEval_RestoreThread(TS); + TS = NULL; + + if (channel) { + switch_channel_set_private(channel, "SwapInThreadState", NULL); + } + + do_hangup_hook(); + + return true; +} + +void Session::setPython(PyObject *state) +{ + Py = state; +} + +void Session::setSelf(PyObject *state) +{ + Self = state; +} + +PyObject *Session::getPython() +{ + return Py; +} + + +bool Session::ready() +{ + bool r; + + sanity_check(false); + r = switch_channel_ready(channel) != 0; + + /*! this is called every time ready is called as a workaround to + make it threadsafe. it sets a flag, and all the places where it + comes in and out of threadswap, check it. so the end result is + you still get the hangup hook executed pretty soon after you + hangup. */ + do_hangup_hook(); + + return r; +} + +void Session::check_hangup_hook() +{ + if (hangup_func && (hook_state == CS_HANGUP || hook_state == CS_ROUTING)) { + hh++; + } +} + +void Session::do_hangup_hook() +{ + PyObject *result, *arglist; + const char *what = hook_state == CS_HANGUP ? "hangup" : "transfer"; + + if (hh && !mark) { + mark++; + + if (hangup_func) { + + if (!PyCallable_Check(hangup_func)) { + switch_log_printf(SWITCH_CHANNEL_LOG, SWITCH_LOG_ERROR, "function not callable\n"); + return; + } + + if (!Self) { + mod_python_conjure_session(NULL, session); + } + + if (hangup_func_arg) { + arglist = Py_BuildValue("(OsO)", Self, what, hangup_func_arg); + } else { + arglist = Py_BuildValue("(Os)", Self, what); + } + + if (!(result = PyEval_CallObject(hangup_func, arglist))) { + PyErr_Print(); + } + + Py_XDECREF(arglist); + Py_XDECREF(hangup_func_arg); + } + } + +} + +static switch_status_t python_hanguphook(switch_core_session_t *session_hungup) +{ + switch_channel_t *channel = switch_core_session_get_channel(session_hungup); + CoreSession *coresession = NULL; + switch_channel_state_t state = switch_channel_get_state(channel); + + if ((coresession = (CoreSession *) switch_channel_get_private(channel, "CoreSession"))) { + if (coresession->hook_state != state) { + coresession->hook_state = state; + coresession->check_hangup_hook(); + } + } + + return SWITCH_STATUS_SUCCESS; +} + + +void Session::setHangupHook(PyObject *pyfunc, PyObject *arg) +{ + + if (!PyCallable_Check(pyfunc)) { + switch_log_printf(SWITCH_CHANNEL_LOG, SWITCH_LOG_WARNING, "Hangup hook is not a python function.\n"); + return; + } + + if (hangup_func) { + if (session) { + switch_core_event_hook_remove_state_change(session, python_hanguphook); + } + Py_XDECREF(hangup_func); + hangup_func = NULL; + } + + if (hangup_func_arg) { + Py_XDECREF(hangup_func_arg); + hangup_func_arg = NULL; + } + + hangup_func = pyfunc; + hangup_func_arg = arg; + + Py_XINCREF(hangup_func); + + if (hangup_func_arg) { + Py_XINCREF(hangup_func_arg); + } + + switch_channel_set_private(channel, "CoreSession", this); + hook_state = switch_channel_get_state(channel); + switch_core_event_hook_add_state_change(session, python_hanguphook); + +} + +void Session::unsetInputCallback(void) +{ + if (cb_function) { + Py_XDECREF(cb_function); + cb_function = NULL; + } + + if (cb_arg) { + Py_XDECREF(cb_arg); + cb_arg = NULL; + } + + args.input_callback = NULL; + ap = NULL; + +} + +void Session::setInputCallback(PyObject *cbfunc, PyObject *funcargs) +{ + + if (!PyCallable_Check(cbfunc)) { + switch_log_printf(SWITCH_CHANNEL_LOG, SWITCH_LOG_WARNING, "Hangup hook is not a python function.\n"); + return; + } + + if (cb_function) { + Py_XDECREF(cb_function); + cb_function = NULL; + } + + if (cb_arg) { + Py_XDECREF(cb_arg); + cb_arg = NULL; + } + + cb_function = cbfunc; + cb_arg = funcargs; + args.buf = this; + switch_channel_set_private(channel, "CoreSession", this); + + Py_XINCREF(cb_function); + + if (cb_arg) { + Py_XINCREF(cb_arg); + } + + args.input_callback = dtmf_callback; + ap = &args; + +} + +switch_status_t Session::run_dtmf_callback(void *input, switch_input_type_t itype) +{ + + PyObject *pyresult, *arglist, *io = NULL; + int ts = 0; + char *str = NULL, *what = ""; + + if (TS) { + ts++; + end_allow_threads(); + } + + if (!PyCallable_Check(cb_function)) { + switch_log_printf(SWITCH_CHANNEL_LOG, SWITCH_LOG_ERROR, "function not callable\n"); + return SWITCH_STATUS_FALSE; + } + + if (itype == SWITCH_INPUT_TYPE_DTMF) { + switch_dtmf_t *dtmf = (switch_dtmf_t *) input; + io = mod_python_conjure_DTMF(dtmf->digit, dtmf->duration); + what = "dtmf"; + } else if (itype == SWITCH_INPUT_TYPE_EVENT){ + what = "event"; + io = mod_python_conjure_event((switch_event_t *) input); + } else { + switch_log_printf(SWITCH_CHANNEL_LOG, SWITCH_LOG_ERROR, "unsupported type!\n"); + return SWITCH_STATUS_FALSE; + } + + if (!Self) { + mod_python_conjure_session(NULL, session); + } + + if (cb_arg) { + arglist = Py_BuildValue("(OsOO)", Self, what, io, cb_arg); + } else { + arglist = Py_BuildValue("(OsO)", Self, what, io); + } + + if ((pyresult = PyEval_CallObject(cb_function, arglist))) { + str = (char *) PyString_AsString(pyresult); + } else { + PyErr_Print(); + } + + Py_XDECREF(arglist); + Py_XDECREF(io); + + if (ts) { + begin_allow_threads(); + } + + if (str) { + return process_callback_result(str); + } + + return SWITCH_STATUS_FALSE; +} diff --git a/src/mod/languages/mod_python3/freeswitch_python.h b/src/mod/languages/mod_python3/freeswitch_python.h new file mode 100644 index 0000000000..6c9dacd410 --- /dev/null +++ b/src/mod/languages/mod_python3/freeswitch_python.h @@ -0,0 +1,49 @@ +#ifndef FREESWITCH_PYTHON_H +#define FREESWITCH_PYTHON_H + +extern "C" { +#include +#include "mod_python_extra.h" +} +#include +namespace PYTHON { + class Session:public CoreSession { + private: + virtual void do_hangup_hook(); + PyObject *getPython(); + PyObject *Py; + PyObject *Self; + int hh; + int mark; + PyThreadState *TS; + public: + Session(); + Session(char *nuuid, CoreSession * a_leg = NULL); + Session(switch_core_session_t *session); + virtual ~ Session(); + + virtual bool begin_allow_threads(); + virtual bool end_allow_threads(); + virtual void check_hangup_hook(); + virtual void destroy(void); + + virtual switch_status_t run_dtmf_callback(void *input, switch_input_type_t itype); + void setInputCallback(PyObject * cbfunc, PyObject * funcargs = NULL); + void unsetInputCallback(void); + void setHangupHook(PyObject * pyfunc, PyObject * arg = NULL); + bool ready(); + + PyObject *cb_function; + PyObject *cb_arg; + PyObject *hangup_func; + PyObject *hangup_func_arg; + + /* keep a pointer to parent module, internal use only */ + void setPython(PyObject * state); + + /* keeps the PyObject * version of the Session so it can be used as args to the callback */ + void setSelf(PyObject * state); + + }; +} +#endif diff --git a/src/mod/languages/mod_python3/hack.diff b/src/mod/languages/mod_python3/hack.diff new file mode 100644 index 0000000000..5732630bba --- /dev/null +++ b/src/mod/languages/mod_python3/hack.diff @@ -0,0 +1,117 @@ +--- mod_python_wrap.cpp.old 2015-06-16 12:56:23.868000000 -0500 ++++ mod_python_wrap.cpp 2015-06-16 12:56:32.268000000 -0500 +@@ -3500,7 +3500,9 @@ SWIG_AsCharArray(PyObject * obj, char *val, size_t size) + if (csize <= size) { + if (val) { + if (csize) memcpy(val, cptr, csize*sizeof(char)); ++#ifndef __clang_analyzer__ + if (csize < size) memset(val + csize, 0, (size - csize)*sizeof(char)); ++#endif + } + if (alloc == SWIG_NEWOBJ) { + delete[] cptr; +@@ -4677,7 +4677,7 @@ SWIGINTERN PyObject *_wrap_DTMF_digit_set(PyObject *SWIGUNUSEDPARM(self), PyObje + char arg2 ; + void *argp1 = 0 ; + int res1 = 0 ; +- char val2 ; ++ char val2 = '\0'; + int ecode2 = 0 ; + PyObject * obj0 = 0 ; + PyObject * obj1 = 0 ; +@@ -4787,7 +4787,7 @@ SWIGINTERN PyObject *_wrap_new_DTMF(PyObject *SWIGUNUSEDPARM(self), PyObject *ar + PyObject *resultobj = 0; + char arg1 ; + uint32_t arg2 = (uint32_t) SWITCH_DEFAULT_DTMF_DURATION ; +- char val1 ; ++ char val1 = '\0'; + int ecode1 = 0 ; + void *argp2 ; + int res2 = 0 ; +@@ -6198,7 +6198,9 @@ + } + arg3 = static_cast< int >(val3); + } ++ Py_BEGIN_ALLOW_THREADS; + result = (Event *)(arg1)->pop(arg2,arg3); ++ Py_END_ALLOW_THREADS; + resultobj = SWIG_NewPointerObj(SWIG_as_voidptr(result), SWIGTYPE_p_Event, SWIG_POINTER_OWN | 0 ); + return resultobj; + fail: +@@ -9264,20 +9266,20 @@ + } + + +-SWIGINTERN PyObject *_wrap_new_Session__SWIG_0(PyObject *SWIGUNUSEDPARM(self), PyObject *args) { ++SWIGINTERN PyObject *_wrap_new_Session__SWIG_0(PyObject *self, PyObject *args) { + PyObject *resultobj = 0; + PYTHON::Session *result = 0 ; + + if (!PyArg_ParseTuple(args,(char *)":new_Session")) SWIG_fail; + result = (PYTHON::Session *)new PYTHON::Session(); +- resultobj = SWIG_NewPointerObj(SWIG_as_voidptr(result), SWIGTYPE_p_PYTHON__Session, SWIG_POINTER_NEW | 0 ); ++ resultobj = SWIG_NewPointerObj(SWIG_as_voidptr(result), SWIGTYPE_p_PYTHON__Session, SWIG_POINTER_NEW | 0 ); result->setPython(self); + return resultobj; + fail: + return NULL; + } + + +-SWIGINTERN PyObject *_wrap_new_Session__SWIG_1(PyObject *SWIGUNUSEDPARM(self), PyObject *args) { ++SWIGINTERN PyObject *_wrap_new_Session__SWIG_1(PyObject *self, PyObject *args) { + PyObject *resultobj = 0; + char *arg1 = (char *) 0 ; + CoreSession *arg2 = (CoreSession *) 0 ; +@@ -9302,7 +9304,7 @@ + } + arg2 = reinterpret_cast< CoreSession * >(argp2); + result = (PYTHON::Session *)new PYTHON::Session(arg1,arg2); +- resultobj = SWIG_NewPointerObj(SWIG_as_voidptr(result), SWIGTYPE_p_PYTHON__Session, SWIG_POINTER_NEW | 0 ); ++ resultobj = SWIG_NewPointerObj(SWIG_as_voidptr(result), SWIGTYPE_p_PYTHON__Session, SWIG_POINTER_NEW | 0 ); result->setPython(self); + if (alloc1 == SWIG_NEWOBJ) delete[] buf1; + return resultobj; + fail: +@@ -9311,7 +9313,7 @@ + } + + +-SWIGINTERN PyObject *_wrap_new_Session__SWIG_2(PyObject *SWIGUNUSEDPARM(self), PyObject *args) { ++SWIGINTERN PyObject *_wrap_new_Session__SWIG_2(PyObject *self, PyObject *args) { + PyObject *resultobj = 0; + char *arg1 = (char *) 0 ; + int res1 ; +@@ -9327,7 +9329,7 @@ + } + arg1 = reinterpret_cast< char * >(buf1); + result = (PYTHON::Session *)new PYTHON::Session(arg1); +- resultobj = SWIG_NewPointerObj(SWIG_as_voidptr(result), SWIGTYPE_p_PYTHON__Session, SWIG_POINTER_NEW | 0 ); ++ resultobj = SWIG_NewPointerObj(SWIG_as_voidptr(result), SWIGTYPE_p_PYTHON__Session, SWIG_POINTER_NEW | 0 ); result->setPython(self); + if (alloc1 == SWIG_NEWOBJ) delete[] buf1; + return resultobj; + fail: +@@ -9336,7 +9338,7 @@ + } + + +-SWIGINTERN PyObject *_wrap_new_Session__SWIG_3(PyObject *SWIGUNUSEDPARM(self), PyObject *args) { ++SWIGINTERN PyObject *_wrap_new_Session__SWIG_3(PyObject *self, PyObject *args) { + PyObject *resultobj = 0; + switch_core_session_t *arg1 = (switch_core_session_t *) 0 ; + void *argp1 = 0 ; +@@ -9351,7 +9353,7 @@ + } + arg1 = reinterpret_cast< switch_core_session_t * >(argp1); + result = (PYTHON::Session *)new PYTHON::Session(arg1); +- resultobj = SWIG_NewPointerObj(SWIG_as_voidptr(result), SWIGTYPE_p_PYTHON__Session, SWIG_POINTER_NEW | 0 ); ++ resultobj = SWIG_NewPointerObj(SWIG_as_voidptr(result), SWIGTYPE_p_PYTHON__Session, SWIG_POINTER_NEW | 0 ); result->setPython(self); + return resultobj; + fail: + return NULL; +@@ -10492,6 +10492,7 @@ SWIGINTERN PyObject *_wrap_Session_setSelf(PyObject *SWIGUNUSEDPARM(self), PyObj + SWIG_exception_fail(SWIG_ArgError(res1), "in method '" "Session_setSelf" "', argument " "1"" of type '" "PYTHON::Session *""'"); + } + arg1 = reinterpret_cast< PYTHON::Session * >(argp1); ++ if (!arg1) SWIG_exception_fail(SWIG_ValueError, "in method '" "Session_setSelf" "', argument " "1"" is NULL"); + arg2 = obj1; + (arg1)->setSelf(arg2); + resultobj = SWIG_Py_Void(); diff --git a/src/mod/languages/mod_python3/mod_python.i b/src/mod/languages/mod_python3/mod_python.i new file mode 100644 index 0000000000..0e8be465ee --- /dev/null +++ b/src/mod/languages/mod_python3/mod_python.i @@ -0,0 +1,36 @@ +%module freeswitch +%include "cstring.i" +%include ../../../../swig_common.i +/** + * tell swig to treat these variables as mutable so they + * can be used to return values. + * See http://www.swig.org/Doc1.3/Library.html + */ +%cstring_bounded_mutable(char *dtmf_buf, 128); +%cstring_bounded_mutable(char *terminator, 8); + +%newobject EventConsumer::pop; +%newobject Session; +%newobject CoreSession; +%newobject Event; +%newobject Stream; +%newobject API::execute; +%newobject API::executeString; +%newobject CoreSession::playAndDetectSpeech; + +/** insert the following includes into generated code so it compiles */ +%{ +#include "switch_cpp.h" +#include "freeswitch_python.h" +%} + + +%ignore SwitchToMempool; + +/** + * tell swig to grok everything defined in these header files and + * build all sorts of c wrappers and python shadows of the c wrappers. + */ +%include switch_swigable_cpp.h +%include freeswitch_python.h + diff --git a/src/mod/languages/mod_python3/mod_python3.c b/src/mod/languages/mod_python3/mod_python3.c new file mode 100644 index 0000000000..d0c7c20df5 --- /dev/null +++ b/src/mod/languages/mod_python3/mod_python3.c @@ -0,0 +1,672 @@ +/* + * FreeSWITCH Modular Media Switching Software Library / Soft-Switch Application + * Copyright (C) 2005-2014, Anthony Minessale II + * + * Version: MPL 1.1 + * + * The contents of this file are subject to the Mozilla Public License Version + * 1.1 (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * http://www.mozilla.org/MPL/ + * + * Software distributed under the License is distributed on an "AS IS" basis, + * WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License + * for the specific language governing rights and limitations under the + * License. + * + * The Original Code is FreeSWITCH Modular Media Switching Software Library / Soft-Switch Application + * + * The Initial Developer of the Original Code is + * Anthony Minessale II + * Portions created by the Initial Developer are Copyright (C) + * the Initial Developer. All Rights Reserved. + * + * Contributor(s): + * + * Brian Fertig + * Johny Kadarisman + * Traun Leyden + * Heimo Stieg + * + * mod_python.c -- Python Module + * + */ + +#include +#include + +#ifndef _REENTRANT +#define _REENTRANT +#endif + +#ifndef _GNU_SOURCE +#define _GNU_SOURCE +#endif + +#include +#include "mod_python_extra.h" +#include + +#define PyString_AsString PyUnicode_AsUTF8 +#define PyString_Check PyUnicode_Check + +PyThreadState *mainThreadState = NULL; + +PyMODINIT_FUNC PyInit__freeswitch(void); +int py_thread(const char *text); +static void set_max_recursion_depth(void); +static switch_api_interface_t python_run_interface; +static void print_python_error(const char * script); + +SWITCH_MODULE_LOAD_FUNCTION(mod_python3_load); +SWITCH_MODULE_SHUTDOWN_FUNCTION(mod_python3_shutdown); +SWITCH_MODULE_DEFINITION_EX(mod_python3, mod_python3_load, mod_python3_shutdown, NULL, SMODF_GLOBAL_SYMBOLS); + +static struct { + switch_memory_pool_t *pool; + char *xml_handler; +} globals; + +struct switch_py_thread { + struct switch_py_thread *prev, *next; + char *cmd; + char *args; + switch_memory_pool_t *pool; + PyThreadState *tstate; +}; +struct switch_py_thread *thread_pool_head = NULL; +static switch_mutex_t *THREAD_POOL_LOCK = NULL; + + + +/** +* This function is similiar to PyErr_Print. It uses the freeswitch print/log mechanism instead of the python sys.stderr +*/ +static void print_python_error(const char * script) +{ + PyObject *pyType = NULL, *pyValue = NULL, *pyTraceback = NULL, *pyString = NULL; + PyObject *pyModule=NULL, *pyFunction = NULL, *pyResult = NULL; + char * buffer = (char*) malloc( 20 * 1024 * sizeof(char)); + /* Variables for the traceback */ + PyTracebackObject * pyTB = NULL/*, *pyTB2 = NULL*/; + char sTemp[256]; + + if (buffer == NULL ) { + switch_log_printf(SWITCH_CHANNEL_LOG, SWITCH_LOG_ERROR, "Not enough Memory to create the error buffer"); + return; + } + + /* just for security that we will always have a string terminater */ + memset(buffer, 0, 20 * 1024 * sizeof(char) ); + + /*Get the errordata*/ + PyErr_Fetch(&pyType, &pyValue, &pyTraceback); + PyErr_NormalizeException(&pyType, &pyValue, &pyTraceback); + + + /* Printing header*/ + sprintf(buffer, "Python Error by calling script \"%s\": ", script ); + + if (pyType != NULL && (pyString=PyObject_Str(pyType))!=NULL && (PyString_Check(pyString))) { + strcat(buffer, PyString_AsString(pyString)); + } else { + strcat(buffer, " "); + } + Py_XDECREF(pyString); + + + /*Print error message*/ + if (pyValue != NULL && (pyString=PyObject_Str(pyValue))!=NULL && (PyString_Check(pyString))) { + strcat(buffer, "\nMessage: "); + strcat(buffer, PyString_AsString(pyString)); + } else { + strcat(buffer, "\nMessage: "); + } + Py_XDECREF(pyString); + + + /* Print the traceback */ + if (pyTraceback != NULL && PyTraceBack_Check(pyTraceback)) { + + /*loading traceback module to create the exception data*/ + pyModule = PyImport_ImportModule("traceback"); + if (pyModule) { + strcat(buffer, "\nException: "); + pyFunction = PyObject_GetAttrString(pyModule, "format_exc"); + if (pyFunction) { + pyResult = PyObject_CallObject(pyFunction, NULL); + if (pyResult && PyString_Check(pyResult)) { + strcat(buffer, PyString_AsString(pyResult)); + } else { + strcat(buffer, ""); + } + Py_XDECREF(pyFunction); + + } + Py_XDECREF(pyModule); + + } + + /* Print traceback header */ + strcat(buffer, "\nTraceback (most recent call last)"); + pyTB = (PyTracebackObject*) pyTraceback; + + /* Traceback */ + do { + sprintf((char*)sTemp, "\n\tFile: \"%s\", line %i, in %s", + PyString_AsString(pyTB->tb_frame->f_code->co_filename), + pyTB->tb_lineno, + PyString_AsString(pyTB->tb_frame->f_code->co_name) ); + strcat(buffer, (char*)sTemp); + + pyTB=pyTB->tb_next; + } while(pyTB != NULL); + } + + PyErr_Restore(pyType,pyValue,pyTraceback); + + switch_log_printf(SWITCH_CHANNEL_LOG, SWITCH_LOG_ERROR, "%s\n", buffer); + + /* free the resources, we dont need memory leaks here */ + free(buffer); +} + + +static void eval_some_python(const char *funcname, char *args, switch_core_session_t *session, switch_stream_handle_t *stream, switch_event_t *params, + char **str, struct switch_py_thread *pt) +{ + PyThreadState *tstate = NULL; + char *dupargs = NULL; + char *argv[2] = { 0 }; + int argc; + char *script = NULL; + PyObject *module_o = NULL, *module = NULL, *sp = NULL, *stp = NULL, *eve = NULL; + PyObject *function = NULL; + PyObject *arg = NULL; + PyObject *result = NULL; + char *p; + + if (str) { + *str = NULL; + } + + if (args) { + dupargs = strdup(args); + } else { + return; + } + + assert(dupargs != NULL); + + if (!(argc = switch_separate_string(dupargs, ' ', argv, (sizeof(argv) / sizeof(argv[0]))))) { + switch_log_printf(SWITCH_CHANNEL_LOG, SWITCH_LOG_ERROR, "No module name specified!\n"); + goto done; + } + + script = strdup(switch_str_nil(argv[0])); + + if ((p = strstr(script, "::"))) { + *p = '\0'; + p += 2; + if (p) { + funcname = p; + } + } + + switch_log_printf(SWITCH_CHANNEL_LOG, SWITCH_LOG_NOTICE, "Invoking py module: %s\n", script); + + tstate = PyThreadState_New(mainThreadState->interp); + if (!tstate) { + switch_log_printf(SWITCH_CHANNEL_LOG, SWITCH_LOG_ERROR, "error acquiring tstate\n"); + goto done; + } + + /* Save state in thread struct so we can terminate it later if needed */ + if (pt) + pt->tstate = tstate; + + // swap in thread state + PyEval_AcquireThread(tstate); + + if (session) { + switch_channel_t *channel = switch_core_session_get_channel(session); + const char *add_path = switch_channel_get_variable(channel, "python_script_path"); + + if (!zstr(add_path)) { + char *buffer = (char*) malloc( 20 * 1024 * sizeof(char)); + if (buffer == NULL ) { + switch_log_printf(SWITCH_CHANNEL_LOG, SWITCH_LOG_ERROR, "Not enough Memory to create the error buffer\n"); + } + + PyRun_SimpleString("import sys"); + switch_log_printf(SWITCH_CHANNEL_LOG, SWITCH_LOG_ERROR, "LOADING path %s", add_path); + + sprintf(buffer, "sys.path.append(\"%s\");", add_path ); + + PyRun_SimpleString(buffer); + + switch_safe_free(buffer); + } + } + + // import the module + module_o = PyImport_ImportModule((char *) script); + if (!module_o) { + switch_log_printf(SWITCH_CHANNEL_LOG, SWITCH_LOG_ERROR, "Error importing module\n"); + print_python_error(script); + PyErr_Clear(); + goto done_swap_out; + } + // reload the module + module = PyImport_ReloadModule(module_o); + if (!module) { + switch_log_printf(SWITCH_CHANNEL_LOG, SWITCH_LOG_ERROR, "Error reloading module\n"); + print_python_error(script); + PyErr_Clear(); + goto done_swap_out; + } + // get the handler function to be called + function = PyObject_GetAttrString(module, (char *) funcname); + if (!function) { + switch_log_printf(SWITCH_CHANNEL_LOG, SWITCH_LOG_ERROR, "Module does not define %s\n", funcname); + print_python_error(script); + PyErr_Clear(); + goto done_swap_out; + } + + PyRun_SimpleString("import freeswitch"); + + if (session) { + sp = mod_python_conjure_session(module, session); + } + + if (params) { + eve = mod_python_conjure_event(params); + } + + if (stream) { + stp = mod_python_conjure_stream(stream); + if (stream->param_event) { + Py_XDECREF(eve); + eve = mod_python_conjure_event(stream->param_event); + } + } + + if (sp && eve && stp) { + arg = Py_BuildValue("(OOOs)", sp, stp, eve, switch_str_nil(argv[1])); + } else if (eve && stp) { + arg = Py_BuildValue("(sOOs)", "na", stp, eve, switch_str_nil(argv[1])); + } else if (eve) { + arg = Py_BuildValue("(Os)", eve, switch_str_nil(argv[1])); + } else if (sp) { + arg = Py_BuildValue("(Os)", sp, switch_str_nil(argv[1])); + } else { + arg = Py_BuildValue("(s)", switch_str_nil(argv[1])); + } + + // invoke the handler + switch_log_printf(SWITCH_CHANNEL_LOG, SWITCH_LOG_DEBUG, "Call python script \n"); + result = PyObject_CallObject(function, arg); + switch_log_printf(SWITCH_CHANNEL_LOG, SWITCH_LOG_DEBUG, "Finished calling python script \n"); + + // check the result and print out any errors + if (result) { + if (str) { + *str = strdup((char *) PyString_AsString(result)); + } + } else if (!PyErr_ExceptionMatches(PyExc_SystemExit)) { + // Print error, but ignore SystemExit + switch_log_printf(SWITCH_CHANNEL_LOG, SWITCH_LOG_ERROR, "Error calling python script\n"); + print_python_error(script); + PyErr_Clear(); + PyRun_SimpleString("python_makes_sense"); + PyGC_Collect(); + } + + done_swap_out: + + + Py_XDECREF(result); + Py_XDECREF(arg); + Py_XDECREF(function); + Py_XDECREF(module); + Py_XDECREF(module_o); + Py_XDECREF(stp); + Py_XDECREF(eve); + Py_XDECREF(sp); + + if (tstate) { + // thread state must be cleared explicitly or we'll get memory leaks + PyThreadState_Clear(tstate); + PyEval_ReleaseThread(tstate); + PyThreadState_Delete(tstate); + } + + done: + + switch_safe_free(dupargs); + switch_safe_free(script); +} + + +static switch_xml_t python_fetch(const char *section, + const char *tag_name, const char *key_name, const char *key_value, switch_event_t *params, void *user_data) +{ + + switch_xml_t xml = NULL; + char *str = NULL; + + if (!zstr(globals.xml_handler)) { + char *mycmd = strdup(globals.xml_handler); + + switch_assert(mycmd); + + eval_some_python("xml_fetch", mycmd, NULL, NULL, params, &str, NULL); + + if (str) { + if (zstr(str)) { + switch_log_printf(SWITCH_CHANNEL_LOG, SWITCH_LOG_ERROR, "No Result\n"); + } else if (!(xml = switch_xml_parse_str((char *) str, strlen(str)))) { + switch_log_printf(SWITCH_CHANNEL_LOG, SWITCH_LOG_ERROR, "Error Parsing XML Result!\n"); + } + switch_safe_free(str); + } + + free(mycmd); + } + + return xml; +} + +static switch_status_t do_config(void) +{ + char *cf = "python.conf"; + switch_xml_t cfg, xml, settings, param; + + if (!(xml = switch_xml_open_cfg(cf, &cfg, NULL))) { + switch_log_printf(SWITCH_CHANNEL_LOG, SWITCH_LOG_ERROR, "Open of %s failed\n", cf); + return SWITCH_STATUS_TERM; + } + + if ((settings = switch_xml_child(cfg, "settings"))) { + for (param = switch_xml_child(settings, "param"); param; param = param->next) { + char *var = (char *) switch_xml_attr_soft(param, "name"); + char *val = (char *) switch_xml_attr_soft(param, "value"); + + if (!strcmp(var, "xml-handler-script")) { + globals.xml_handler = switch_core_strdup(globals.pool, val); + } else if (!strcmp(var, "xml-handler-bindings")) { + if (!zstr(globals.xml_handler)) { + switch_log_printf(SWITCH_CHANNEL_LOG, SWITCH_LOG_INFO, "binding '%s' to '%s'\n", globals.xml_handler, val); + switch_xml_bind_search_function(python_fetch, switch_xml_parse_section_string(val), NULL); + } + } else if (!strcmp(var, "startup-script")) { + if (val) { + py_thread(val); + } + } + } + } + + switch_xml_free(xml); + + return SWITCH_STATUS_SUCCESS; +} + + +/** + * As freeswitch runs with a smaller than normal stack size (240K instead of the usual value .. 1 or 2 MB), + * we must decrease the default python recursion limit accordingly. Otherwise, python can easily blow + * up the stack and the whole switch crashes. See modlang-134 + */ +static void set_max_recursion_depth(void) +{ + + // assume that a stack frame is approximately 1K, so divide thread stack size (eg, 240K) by + // 1K to get the approx number of stack frames we can hold before blowing up. + int newMaxRecursionDepth = SWITCH_THREAD_STACKSIZE / 1024; + + PyObject *sysModule = PyImport_ImportModule("sys"); + PyObject *setRecursionLimit = PyObject_GetAttrString(sysModule, "setrecursionlimit"); + PyObject *recLimit = Py_BuildValue("(i)", newMaxRecursionDepth); + PyObject *setrecursion_result = PyObject_CallObject(setRecursionLimit, recLimit); + if (setrecursion_result) { + switch_log_printf(SWITCH_CHANNEL_LOG, SWITCH_LOG_DEBUG, "Set python recursion limit to %d\n", newMaxRecursionDepth); + } else { + switch_log_printf(SWITCH_CHANNEL_LOG, SWITCH_LOG_ERROR, "Failed to set recursion limit to %d\n", newMaxRecursionDepth); + print_python_error("_freeswitch"); + PyErr_Clear(); + PyRun_SimpleString("python_makes_sense"); + PyGC_Collect(); + } + + +} + +SWITCH_STANDARD_APP(python_function) +{ + eval_some_python("handler", (char *) data, session, NULL, NULL, NULL, NULL); + +} + +static void *SWITCH_THREAD_FUNC py_thread_run(switch_thread_t *thread, void *obj) +{ + switch_memory_pool_t *pool; + struct switch_py_thread *pt = (struct switch_py_thread *) obj; + + /* Put thread in pool so we keep track of our threads */ + switch_mutex_lock(THREAD_POOL_LOCK); + pt->next = thread_pool_head; + pt->prev = NULL; + if (pt->next) + pt->next->prev = pt; + thread_pool_head = pt; + switch_mutex_unlock(THREAD_POOL_LOCK); + + /* Run the python script */ + eval_some_python("runtime", pt->args, NULL, NULL, NULL, NULL, pt); + + /* Thread is dead, remove from pool */ + switch_mutex_lock(THREAD_POOL_LOCK); + if (pt->next) + pt->next->prev = pt->prev; + if (pt->prev) + pt->prev->next = pt->next; + if (thread_pool_head == pt) + thread_pool_head = pt->next; + switch_mutex_unlock(THREAD_POOL_LOCK); + + pool = pt->pool; + switch_core_destroy_memory_pool(&pool); + + return NULL; +} + +SWITCH_STANDARD_API(api_python) +{ + + eval_some_python("fsapi", (char *) cmd, session, stream, NULL, NULL, NULL); + + return SWITCH_STATUS_SUCCESS; +} + +int py_thread(const char *text) +{ + switch_thread_t *thread; + switch_threadattr_t *thd_attr = NULL; + switch_memory_pool_t *pool; + struct switch_py_thread *pt; + + switch_core_new_memory_pool(&pool); + assert(pool != NULL); + + pt = switch_core_alloc(pool, sizeof(*pt)); + assert(pt != NULL); + + pt->pool = pool; + pt->args = switch_core_strdup(pt->pool, text); + + switch_threadattr_create(&thd_attr, pt->pool); + switch_threadattr_detach_set(thd_attr, 1); + switch_threadattr_stacksize_set(thd_attr, SWITCH_THREAD_STACKSIZE); + switch_thread_create(&thread, thd_attr, py_thread_run, pt, pt->pool); + + return 0; +} + +SWITCH_STANDARD_API(launch_python) +{ + + if (zstr(cmd)) { + stream->write_function(stream, "USAGE: %s\n", python_run_interface.syntax); + return SWITCH_STATUS_SUCCESS; + } + + py_thread(cmd); + stream->write_function(stream, "OK\n"); + return SWITCH_STATUS_SUCCESS; +} + + +SWITCH_STANDARD_CHAT_APP(python_chat_function) +{ + eval_some_python("chat", (char *) data, NULL, NULL, message, NULL, NULL); + return SWITCH_STATUS_SUCCESS; + +} + +SWITCH_MODULE_LOAD_FUNCTION(mod_python3_load) +{ + switch_api_interface_t *api_interface; + switch_application_interface_t *app_interface; + switch_chat_application_interface_t *chat_app_interface; + + char *pp = getenv("PYTHONPATH"); + + if (pp) { + char *path = switch_mprintf("%s:%s", pp, SWITCH_GLOBAL_dirs.script_dir); + setenv("PYTHONPATH", path, 1); + free(path); + } else { + setenv("PYTHONPATH", SWITCH_GLOBAL_dirs.script_dir, 1); + } + + switch_log_printf(SWITCH_CHANNEL_LOG, SWITCH_LOG_NOTICE, "Python Framework Loading...\n"); + + globals.pool = pool; + + if (!Py_IsInitialized()) { + + /* Add a built-in module, before Py_Initialize */ + if (PyImport_AppendInittab("_freeswitch", PyInit__freeswitch) == -1) { + fprintf(stderr, "Error: could not extend in-built modules table\n"); + } + + // initialize python system + Py_Initialize(); + + // save threadstate since it's interp field will be needed + // to create new threadstates, and will be needed for shutdown + mainThreadState = PyThreadState_Get(); + + // set the maximum recursion depth + set_max_recursion_depth(); + + // swap out threadstate since the call threads will create + // their own and swap in their threadstate + // and release the global interpreter lock + PyEval_SaveThread(); + + } + + switch_mutex_init(&THREAD_POOL_LOCK, SWITCH_MUTEX_NESTED, pool); + + do_config(); + + /* connect my internal structure to the blank pointer passed to me */ + *module_interface = switch_loadable_module_create_module_interface(pool, modname); + SWITCH_ADD_API(api_interface, "pyrun", "run a python script", launch_python, "python "); + SWITCH_ADD_API(api_interface, "python", "run a python script", api_python, "python "); + SWITCH_ADD_APP(app_interface, "python", "Launch python ivr", "Run a python ivr on a channel", python_function, "